Angular6 - ngIf 不会破坏对象

Angular6 - ngIf does not destroy object

我有一个父组件,它会在单击按钮时更改作为 @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>

在 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)再次打开将导致组件被销毁并重新创建。

我遇到了类似的问题。在我看来使用 changeDetectorsetTimeout

更优雅
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,[])}})
}