【问题标题】:Angular 2+ - Set ngModel to null when ngIf causes hideAngular 2+ - 当 ngIf 导致隐藏时将 ngModel 设置为 null
【发布时间】:2018-12-01 09:45:42
【问题描述】:

我有一个类似Reset ngModel values on ngIf in angular2的问题

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

如果我的情况很简单,我不会问这个。如果是这种情况,那么我只需重置 *ngIf 值的更改,但由于我的表单具有多个级别的 *ngIf 嵌套,并且多个 *ngIfs 会导致某些元素显示/隐藏,我想使用某种指令来完成重置。

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

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

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

【问题讨论】:

    标签: angular angular2-template angular2-forms angular2-directives


    【解决方案1】:

    您可以利用DoCheck Lifecycle 挂钩来设置值。

    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

    【讨论】:

    • 就像我说的,我的情况比这复杂得多,处理大量 *ngIfs 和输入控件的所有组合会使创建/维护 ngDoCheck() 变得非常麻烦。在这样做之前,我会将所有输入控件转换为自定义组件。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-04-12
      • 2017-06-11
      • 2017-11-07
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多