要实现Angular 8中的递归表单,可以按照以下步骤进行操作:
ng new recursive-form
cd recursive-form
npm install
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-recursive-form',
templateUrl: './recursive-form.component.html',
styleUrls: ['./recursive-form.component.css']
})
export class RecursiveFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['', Validators.required],
subForms: this.fb.array([])
});
}
addSubForm() {
const subForms = this.form.get('subForms') as FormArray;
subForms.push(this.fb.group({
name: ['', Validators.required],
subForms: this.fb.array([])
}));
}
removeSubForm(index: number) {
const subForms = this.form.get('subForms') as FormArray;
subForms.removeAt(index);
}
onSubmit() {
console.log(this.form.value);
}
}
ng serve
这样,你就可以在Angular 8中创建一个递归表单了。你可以根据需要对表单进行扩展和自定义。