“AbstractControl
<div class="form-group" formArrayName="skills">
<ng-container *ngFor="let skill of reactiveForm.get('skills')['controls']; let i = index;">
<label for="Skills">Skills</label>
<input type="text">
</ng-container>
</div>
reactiveForm!: FormGroup;
ngOnInit(): void {
this.reactiveForm = new FormGroup({
// To set default value we need to pass this value instead of null.
firstname: new FormControl(null, Validators.minLength(4)),
lastname: new FormControl(null, Validators.required),
email: new FormControl('[email protected]', [Validators.required, Validators.email]),
country: new FormControl('Canada'),
gender: new FormControl('male'),
hobbies: new FormControl(null),
skills: new FormArray([
new FormControl(null),
])
})
}
onSubmit() {
console.log(this.reactiveForm);
}
}
在 ts 文件中编写技能的 getter
get skills() {
return this.reactiveForm.get('skills') as FormArray;
}
以及在 HTML
<div class="form-group" formArrayName="skills">
<ng-container *ngFor="let skill of skills.controls; let i = index;">
<label for="Skills">Skills</label>
<input type="text">
</ng-container>
</div>