【问题标题】:Angular6 - ngIf does not destroy objectAngular6 - ngIf 不会破坏对象
【发布时间】:2019-03-01 13:40:55
【问题描述】:

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

【问题讨论】:

  • 我没有时间真正考虑这么多,但我只是想指出您正在绑定到一个对象。然后父级更改对对象的引用而不实际更改对象。我不希望孩子意识到任何事情都发生了变化。
  • 您提供的代码中没有 ngIf。请在堆栈闪电战中重现问题。
  • @danday74 哈哈
  • @danday74 很抱歉。我刚刚添加了它。
  • 您不能使用 *ngIf 来销毁正在被另一个元素使用的子元素。我昨天真的发现了

标签: angular angular6 form-control


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我有类似的问题。在我看来使用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,[])}})
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-10
      • 2021-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多