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

时间:2018-06-22 00:19:32

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

我遇到的问题类似于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 :(得分:0)

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

答案 1 :(得分:0)

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

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