我正在研究Angular 4项目.我需要检测表单控件数组的更改.例如我有一个名为providers的表单控件数组,如何检测其更改?
export class CustomFormArray { public form: FormGroup; constructor(private _fb: FormBuilder) { this.form = _fb.group({ providers: _fb.array([]) }); } }
FormArray扩展了AbstractControl,因此它具有发出chanes的valueChanges属性.
this.form = this.fb.group({ providers: this.fb.array([]),}); (this.form.get('providers') as FormArray).push(new FormControl('',Validators.required)); (this.form.get('providers') as FormArray).push(new FormControl('',Validators.required)); (this.form.get('providers') as FormArray).valueChanges.subscribe(values => { console.log(values); });
在您的模板中:
<input *ngFor="let field of form.controls.providers.controls;" [formControl]="field">
subscribe中的值将在任何更改(语法或来自UI)时返回具有每个输入字段值的数组.
如果FormArray中有FormGroup,则无需更改.只需使用以下组件代码.
(this.form.get('providers') as FormArray).push(this.fb.group({ 'name': '','age': '' }));
和模板将是:
<div *ngFor="let field of form.controls.providers.controls;" [formGroup]="field"> <input formControlName="name" placeholder="name"> <input formControlName="age" placeholder="age"> </div>
这是plunker