将自定义窗体控件添加到窗体数组时未触发验证



我有一个表单组,其中包含一系列自定义表单控件(自定义表单控件也有验证(。每当我将新的窗体控件推送到数组时,完整窗体的验证都无法正常运行。

似乎在推送新窗体控件时,首先运行父窗体控件的验证,然后仅运行子窗体控件的验证。有人知道为什么吗?

请参阅 https://stackblitz.com/edit/angular-fh6vzw?embed=1&file=src/app/app.component.ts 的堆栈闪电战链接

你需要给 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管理表单

那就是我们的应用程序组件

<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
}

最新更新