标签: angular2-formbuilder

如何使用Angular2 Formbuilder处理文件上传?

似乎Angular Docs缺乏适当的文档.Angular2最终版本仍然更年轻,因此互联网上没有太多帮助.

如果有人可以指导我使用Angular 2.1中的 FormBuilder组件来处理文件上传,我将不胜感激

file-upload angular2-formbuilder typescript2.0 angular

5
推荐指数
1
解决办法
657
查看次数

关键字的Angular 2强制自定义验证

我有这个代码:

this.form = fb.group({
        username: ['', Validators.compose([Validators.required])],
        fullName: ['', Validators.compose([Validators.required])],
        password: ['', Validators.compose([Validators.required])],
        confirmPassword: ['', Validators.required],
    }, {validator: matchingPasswords('password', 'confirmPassword')});
Run Code Online (Sandbox Code Playgroud)

matchingPasswords:

export function matchingPasswords(passwordKey: string, passwordConfirmationKey: string) {
return (group: FormGroup) => {
    let password = group.controls[passwordKey];
    let passwordConfirmation = group.controls[passwordConfirmationKey];
    if (password.value !== passwordConfirmation.value) {
        return passwordConfirmation.setErrors({mismatchedPasswords: true})
    }
}
Run Code Online (Sandbox Code Playgroud)

}

HTML:

<div class="form-group">
        <input [formControl]="confirmPassword" class="form-control checking-field" type="password">
        <span class="help-block text-danger" *ngIf="form.get('password').touched && form.get('password').hasError('required')">
</div>
<div class="form-group">
        <input class="custom-control-input checkbox-main" type="checkbox" [(ngModel)]="policyButtonValue" [ngModelOptions]="{standalone: true}" ngDefaultControl>
        <span class="custom-control-indicator"></span>
</div> …
Run Code Online (Sandbox Code Playgroud)

validation angular2-formbuilder angular

5
推荐指数
1
解决办法
2534
查看次数

Angular - 反应式表单 - 如何使用类和验证器将对象传递到 FormGroup

我要创建一个大型表单,并决定使用反应式表单功能以方便使用。然而,我面临着一些可能显而易见的挑战并寻求帮助。

下面是两种情况,除了验证之外,它们产生相同的结果。该createFormWithValidation()方法指定了每个控件及其关联的验证器。该方法仅使用对象但不添加验证器createFromPassingObject()来创建相同的表单。this.party

我的目标是将一个对象传递给this.fb.group()该对象,该对象将具有属于该类的控件,并且能够为该类的每个属性指定验证器Party

// The Class with the properties
export class Party {
  firstName: string = '';
  lastName: string = '';

  constructor() {}
}

// party Object
myForm: FormGroup;
this.party = new Party();

// Form with explicit controls and their validators

createFormWithValidation() {
  this.myForm = this.fb.group({
    firstName: [this.party.firstName, [Validators.required, Validators.minLength(3)]],
    lastName: [this.party.lastName, [Validators.required, Validators.minLength(3)]]
  })
}

// The goal is to achieve this type of method where this.party will be the …
Run Code Online (Sandbox Code Playgroud)

angular2-formbuilder angular angular-reactive-forms

5
推荐指数
1
解决办法
1万
查看次数

如何在没有ng-model的情况下以角度2形式以编程方式更改原始属性

我是Angular 2框架的新手.我感谢任何帮助.

我在角2中有通常的组件:

import {FORM_DIRECTIVES, FormBuilder, Validators} from 'angular2/common';

export class TestComponent {
    public values = ['value1', 'value2', 'value3', 'value4'];
}
Run Code Online (Sandbox Code Playgroud)

然后我注入FormBuilder构造函数:

@Inject(FormBuilder) public fb
Run Code Online (Sandbox Code Playgroud)

HTML包含下一个标记:

<input [(ngModel)]="formData.title" type="text" class="form-control" ngControl="title">
Run Code Online (Sandbox Code Playgroud)

标题和描述非常有用.但我添加了bootstrap下拉列表,它没有任何表单元素.

<div *ngFor="#value of values" (click)="onValueChanged(value)" class="dropdown-item">{{value}}</div>
Run Code Online (Sandbox Code Playgroud)

所以,问题是html标记不包含任何模型.我试图解决这个问题的方法是创建函数onValueChanged

 onValueChanged(value){
    this.formData.controls.value.updateValue(value);
    this.formData.value = value;
    console.log(this.formData.pristine) //Still true :(
}
Run Code Online (Sandbox Code Playgroud)

这两行都不起作用,因为this.formData.pristine下拉列表更改后没有更改.

现在我正在考虑如何更新FormBuilder,例如,有一些方法可以this.fb.update()

javascript angular2-forms angular2-formbuilder angular

4
推荐指数
1
解决办法
5737
查看次数

如何以编程方式检查表单控件在Angular中是否有效?

我需要检入组件(不在模板中)是否由formBuilder生成的控件有效。我试过了:

if(this.miSpecialForm.controls.miName.dirty){
 console.log('Hi mom!');
}
Run Code Online (Sandbox Code Playgroud)

但是我得到了错误:

Property 'miName' does not exist on type '{ [key: string]: AbstractControl; }'
Run Code Online (Sandbox Code Playgroud)

angular2-formbuilder angular

4
推荐指数
2
解决办法
8403
查看次数

angular2 formBuilder组异步验证

我正在尝试实现异步验证器但没有成功......

我的组件创建了一个表单:

this.personForm = this._frmBldr.group({
  lastname:  [ '', Validators.compose([Validators.required, Validators.minLength(2) ]) ],
  firstname: [ '', Validators.compose([Validators.required, Validators.minLength(2) ]) ],
  birthdate: [ '', Validators.compose([ Validators.required, DateValidators.checkIsNotInTheFuture ]) ],
  driverLicenceDate: [ '', Validators.compose([ Validators.required, DateValidators.checkIsNotInTheFuture ]), this.asyncValidationLicenceDate.bind(this) ],
}, {
  asyncValidator: this.validateBusiness.bind(this),
  validator: this.validateDriverLicenseOlderThanBirthdate,
});
Run Code Online (Sandbox Code Playgroud)

我的验证方法

validateBusiness(group: FormGroup) {
  console.log('validateBusiness')
  return this._frmService
    .validateForm(group.value)
    .map((validationResponse: IValidationResponse) => {
      if (validationResponse) {
        validationResponse.validations.forEach( (validationError: IValidationErrorDescription) => {
                        let errorMsg = validationError.display;
                        let errorCode = validationError.code;
                        validationError.fields.forEach( (fieldName: string) => {
                            console.log(fieldName);
                            let control = …
Run Code Online (Sandbox Code Playgroud)

validation angular2-forms angular2-formbuilder angular

4
推荐指数
1
解决办法
5100
查看次数

在FormBuilder中使用嵌套对象

所以我有这种形式,它工作正常..但现在我想扩展一些json结构...

https://plnkr.co/edit/aYaYTBRHekHzyS0M7HDM?p=preview

我想要使​​用的新结构看起来像这样(只有地址:已更改):

  email: ['', [Validators.required, Validators.email]],
  password: ['', [Validators.required, Validators.minLength(5)]],
  address: this.fb.array([{
    name: '',
    addressLine1: ['', [Validators.required]],
    city: ['', [Validators.required]],
    postalCode: [Validators.required],
  }]),
Run Code Online (Sandbox Code Playgroud)

但我不断收到错误,如"ERROR TypeError:control.registerOnChange不是函数".想通知这与formControlName缺失有关,但我不希望所有数据都显示..

在输入字段中,我只想显示addressLine1(根本不显示name,city或postalCode).

forms angular2-formbuilder angular

4
推荐指数
1
解决办法
6931
查看次数

patch使用angular2在嵌套表单控件中的值

我需要在FormBuiler中的嵌套控件中设置一个值,模型如下:

this.addAccForm = this.fb.group({
      accid: ['', Validators.required],
      status: '',
      cyc: this.fb.array([
        this.initCyc(),
      ])
    })

initCyc() {
      return this.fb.group({
        cycid: ['', Validators.required],
        name: ['', Validators.required],
        description: ['', Validators.required],
        status: ['', Validators.required],
        det: this.fb.group({
            dcycid: ['', Validators.required],
            status: ['', Validators.required]
        })
      })
Run Code Online (Sandbox Code Playgroud)

我需要设置一个值cycid和dcycid但我坚持它,我试图使用以下行,但它没有帮助:

this.addAccForm.patchValue({cyc: { [0]: {cycid: 1234567 }}});
Run Code Online (Sandbox Code Playgroud)

//

this.addAccForm.patchValue({cyc: { [0]: { det : {dcycid: 9876543}}}});
Run Code Online (Sandbox Code Playgroud)

知道它应该怎么样?

angular2-forms angular2-formbuilder

4
推荐指数
4
解决办法
6698
查看次数

FormControl:setValue 不触发输入事件

我有一个表单,其notes字段以 textarea 为界。

this.form = this.formBuilder.group({});
this.form.addControl('notes', new FormControl(''));
Run Code Online (Sandbox Code Playgroud)

该模板autoresize附有一个指令。

<textarea formControlName="notes" autosize></textarea>
Run Code Online (Sandbox Code Playgroud)

每次用户更改其内容时,这样的指令都会调整 textarea 的高度。

@HostListener('input')
public onChange(textArea: HTMLTextAreaElement): void {
    const textarea = this.element.nativeElement.querySelector('textarea');
    this.renderer.setStyle(textarea, 'overflow', 'hidden');
    this.renderer.setStyle(textarea, 'height', 'auto');
    this.renderer.setStyle(textarea, 'height', `${textarea.scrollHeight}px`);
  }
Run Code Online (Sandbox Code Playgroud)

但是,当我以编程方式更改 FormControl 的值时,input不会触发该事件,并且不会相应地调整 textarea 的大小。

this.form.controls['notes'].setValue('a new value'); // not firing events
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

events angular2-formbuilder angular

4
推荐指数
1
解决办法
2068
查看次数

Angular - 使用 ngFor 将自定义(数据)属性添加到 &lt;option&gt;

我需要添加自定义数据属性来选择选项。我想要它,因为在更改时我想根据所选属性(而不是值)触发操作

这是我正在使用的代码

<select (domChange)="onListUpdate($event)" formControlName="region" id="region" class="selectric form-control">
    <option code="" value="-1">{{ 'select_country' | translate }}</option>
    <option data-isocode="{{region.iso_code}}" value="{{region.id}}" *ngFor="let region of regions">{{region.name['en']}}</option>
</select>
Run Code Online (Sandbox Code Playgroud)

例如,当我为数据属性赋予静态值时,它可以工作,以下工作没有任何问题(注意数据 isocode 具有静态值)

<option data-isocode="abc" value="{{region.id}}" *ngFor="let region of regions">{{region.name['en']}}</option>
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试在 data-isocode 中使用变量时

<option data-isocode="{{region.iso_code}}" value="{{region.id}}" *ngFor="let region of regions">{{region.name['en']}}</option>
Run Code Online (Sandbox Code Playgroud)

它引发了我以下错误

Can't bind to 'isocode' since it isn't a known property of 'option'
Run Code Online (Sandbox Code Playgroud)

如何使用 Angular 传递数据属性(如 jQuery)并使用 FormBuilder 获取值?

angular2-formbuilder angular angular7

4
推荐指数
1
解决办法
5373
查看次数