【发布时间】:2019-01-04 17:18:45
【问题描述】:
用户数组可以有多个元素(用户)。在模板中,我遍历这个数组并为每个元素添加一个表单。现在每个表单都绑定到相同的表单组值。如果我为第一个用户填写表单,所有表单的提交按钮都会启用。如何将每个表单指向唯一的 formGroup 或唯一的变量?
组件:
import { FormControl, FormGroup, Validators, FormBuilder} from '@angular/forms';
...
export class UserComponent implements OnInit {
form: FormGroup;
@input users: any[];
constructor(private _fb: FormBuilder) {}
ngOnInit() {
this.form = this._fb.group({
address: new FormControl('', [Validators.required]),
phone: new FormControl('', [Validators.required]),
});
}
add() {
if (this.form.valid){
// code
}
}
模板:
<div *ngFor="let user if users">
{{user.name}}
<form [formGroup]="form" (ngSubmit)="add()">
<div class="form-group">
<label>Address:</label>
<input formControlName="address" class="form-control">
<label>Phone:</label>
<input formControlName="phone" class="form-control"></input>
</div>
<button type="submit" class="submit" [disabled]="!form.valid">Submit</button>
</form>
</div>
【问题讨论】:
标签: angular angular-reactive-forms reactive-forms