你需要给 Angular 一个呼吸,就在你的 onAddHero 函数中,添加一个 setTimeout(()=>heroesArray.updateValueAndValidity()
onAddHero() {
const heroesArray = this.formGroup.get('heroes') as FormArray;
heroesArray.push(new FormControl({
name: '',
wealth: ''
}));
//this lines
setTimeout(()=>{
heroesArray.updateValueAndValidity()
})
console.log('hero added');
}
顺便说一句,我认为这是一种“奇怪”的做事方式,对我来说更简单的是使用 @Input 和 @Ouput 创建组件并从 app.component 管理表单
这就是我们的 app.component
<form [formGroup]="newForm" (submit)="onSubmit()">
<div class="form-group">
<label>Collection name<input formControlName="collectionName" class="form-control" /></label>
</div>
<app-comic-book [form]="newForm.get('comicBook')" (addHero)="addHero()"></app-comic-book>
<button type="submit" [disabled]="!newForm.valid" class="btn btn-primary">Submit</button>
</form>
newForm: FormGroup = this.fb.group({
collectionName: 'classics 1',
comicBook: this.fb.group({
name: 'volume 1',
heroes: this.fb.array([
this.createHeroe({
name: 'Superman',
wealth: 'Piss poor'
}),
this.createHeroe({
name: 'Batman',
wealth: 'Crazy rich'
})
])
})
});
constructor(private fb: FormBuilder) { }
createHeroe(data)
{
data=data || {name:'',wealth:''}
return this.fb.group({
name:[data.name,Validators.required],
wealth:[data.wealth,Validators.required]
})
}
addHero()
{
const heroes=this.newForm.get('comicBook.heroes') as FormArray;
heroes.push(this.createHeroe(null))
}
onSubmit() {
console.log(this.newForm);
}
我们的漫画书组件
<div [formGroup]="formGroup">
<div class="form-group">
<label>Comicbook name<input formControlName="name" class="form-control" /></label>
</div>
<div formArrayName="heroes">
<div *ngFor="let hero of formGroup.get('heroes').controls; let i = index">
<app-hero [form]="hero"></app-hero>
</div>
</div>
<button (click)="onAddHero()" class="btn btn-primary">Add Hero</button>
</div>
export class ComicBookComponent {
@Input('form')formGroup
@Output()addHero = new EventEmitter<any>();
onAddHero()
{
this.addHero.emit()
}
}
还有我们的英雄组件
<div [formGroup]="formGroup">
<div class="form-group">
<label>Hero name<input formControlName="name" class="form-control" /></label>
</div>
<div class="form-group">
<label>Hero wealth<input formControlName="wealth" class="form-control" /></label>
</div>
</div>
export class HeroComponent {
@Input('form')formGroup
}