我有一个父组件,该组件将更改单击按钮时作为@Input()
传递的子窗体。我使用ngIf
来渲染子组件,但是当我单击以更改表单时,子组件不会被销毁并重新创建。
parent.component.ts
form: FormGroup;
showChildForm: boolean;
num: number;
ngOnInit(){
this.showChildForm = false;
this.num = 1;
this.form = new FormGroup({group:{'name', new FormControl('name'+this.num,[])}})
}
changeForm(){
this.num += 1;
this.showChildForm = true;
this.form = new FormGroup({group:{'name', new FormControl('name'+this.num,[])}})
}
parent.component.html
<button (click)="changeForm()"></button>
<child *ngIf="showChildForm" [form]="form"></child>
child.component.ts
@Input() form: FormGroup;
child.component.html
<form [formGroup]="form">
<input type="text" [formControl]="form.get('name')"/>
</form>
答案 0 :(得分:3)
在changeForm内,您无需将this.showChildForm再次设置为false。
尝试这样做:
changeForm(){
this.num += 1;
this.showChildForm = false;
setTimeout(() => {
this.showChildForm = true;
this.form = new FormGroup({group:{'name', new FormControl('name'+this.num,[])}})
})
}
希望将其切换为关闭状态,然后在下一个刻度周期(使用setTimeout)中再次打开,将导致该组件被破坏并重新创建。
答案 1 :(得分:0)
我有类似的问题。我认为使用changeDetector
比setTimeout
constructor(private changeDetector: ChangeDetectorRef){}
changeForm() {
this.num += 1;
this.showChildForm = false;
// now notify angular to check for updates
this.changeDetector.detectChanges();
// change detection should remove the component now
// then we can enable it again to create a new instance
this.showChildForm = true;
this.form = new FormGroup({group:{'name', new FormControl('name'+this.num,[])}})
}