简体   繁体   English

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

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

I have an issue similar to Reset ngModel values on ngIf in angular2 我有一个类似于在angular2中的ngIf上重置ngModel值的问题

I would like to set any ngModel values to null whenever a parent *ngIf causes that element to be hidden. 每当父* ngIf导致该元素被隐藏时,我想将任何ngModel值设置为null。

I wouldn't be asking this if my situation was simple. 如果我的情况很简单,我不会问这个。 If that were the case, then I'd just reset on the change of the *ngIf value, but since my form has multiple levels of *ngIf nesting and multiple *ngIfs can cause some elements to show/hide, I'd like to use some sort of directive to accomplish the resetting. 如果是这种情况,那么我将仅对* ngIf值的更改进行重置,但是由于我的表单具有多个* ngIf嵌套级别,并且多个* ngIfs可以导致某些元素显示/隐藏,所以我想使用某种指令来完成重置。

I'd rather not have to convert all my simple input elements to components to take advantage of the OnDestroy event, so before I do that, I want to see if there's some other way. 我宁可不必将所有简单的输入元素都转换为组件以利用OnDestroy事件,因此在执行此操作之前,我想看看是否还有其他方法。

I've created a StackBlitz project to illustrate what I want to do. 我创建了一个StackBlitz项目来说明我想要做什么。 In this project, is there a way to implement the (ngOnDestroy) event? 在此项目中,有没有一种方法可以实现(ngOnDestroy)事件?

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

you can leverage the DoCheck Lifecycle hook to set the values. 您可以利用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

I came up with a solution. 我想出了一个解决方案。 The following project has a directive that binds to the ngModel and uses the directive's OnDestroy event to trigger setting the ngModel to null. 以下项目具有绑定到ngModel的指令,并使用该指令的OnDestroy事件触发将ngModel设置为null。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM