首页 文章

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

提问于
浏览
0

我有类似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

2 回答

  • 0

    您可以利用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

  • 0

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

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

相关问题