Angular 2+ - 当 ngIf 导致隐藏时将 ngModel 设置为 null

Angular 2+ - Set ngModel to null when ngIf causes hide

我遇到了类似于

的问题

每当父 *ngIf 导致该元素被隐藏时,我想将任何 ngModel 值设置为 null。

如果我的情况很简单,我不会问这个。如果是这样的话,那么我只是在 *ngIf 值的变化时重置,但由于我的表单有多个 *ngIf 嵌套级别并且多个 *ngIfs 会导致某些元素 show/hide,我会喜欢使用某种指令来完成重置。

我不想将我所有的简单输入元素都转换为组件来利用 OnDestroy 事件,所以在我这样做之前,我想看看是否有其他方法。

我创建了一个 StackBlitz 项目来说明我想做什么。在这个项目中,有没有办法实现(ngOnDestroy)事件?

https://stackblitz.com/edit/angular-7dgpwr?file=src%2Fapp%2Fapp.component.html

您可以利用 DoCheck 生命周期挂钩来设置值。

ngDoCheck()
  {
    if(!this.outerBoxVisible)
    {
      this.outerTextValue=null;
      console.log('outertextvalue='+this.outerTextValue);
    }
     if(!this.innerBoxVisible)
    {
      this.outerTextValue=null;
      console.log('innertextvalue='+this.outerTextValue);
    }
  }

Forked Stackblitz

我想出了一个解决办法。以下项目有一个绑定到 ngModel 的指令,并使用指令的 OnDestroy 事件触发将 ngModel 设置为 null。

https://stackblitz.com/edit/angular-4uwdmi?file=src%2Fapp%2Fapp.component.html