【发布时间】:2022-12-14 14:17:42
【问题描述】:
为什么会出现此错误,以及如何修复它: TS2740:类型“AbstractControl<any, any>”缺少类型“FormGroup”中的以下属性:controls、registerControl、addControl、removeControl 等 2 个。
我的 HTML:
<button type="button" (click)="addName()">Add Name</button>
<div formArrayName="names">
<div *ngFor="let nm of getNames.controls">
<div [formGroup]="nm"> //THIS LINE IS GIVING ERROR
<input formControlName="fname" type="text" placeholder="First Name">
<input formControlName="lname" type="text" placeholder="Last Name">
</div>
</div>
</div>
<div>
<button type="submit">Submit</button>
</div>
我的 ts:
export class TestComponent implements OnInit {
constructor(private fb: FormBuilder) { }
form = this.fb.group({
names: this.fb.array([])
});
get getNames(){
return this.form.controls["names"] as FormArray;
}
addName(){
const newName = this.fb.group({
fname: ['', Validators.required],
lname: ['', Validators.required]
});
this.getNames.push(newName);
}
onSubmit():void{
console.log(this.form.value)
}
ngOnInit(): void {
}
}
【问题讨论】:
标签: angular-reactive-forms angular-forms angular-formbuilder