Вам нужно сделать выдох 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);
}
Наш коми c -book.component
<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
}