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

大兔子大兔子 提交于 2019-12-02 20:32:07

问题


I have an issue similar to Reset ngModel values on ngIf in angular2

I would like to set any ngModel values to null whenever a parent *ngIf causes that element to be hidden.

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.

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.

I've created a StackBlitz project to illustrate what I want to do. In this project, is there a way to implement the (ngOnDestroy) event?

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


回答1:


you can leverage the DoCheck Lifecycle hook to set the values.

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




回答2:


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.

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



来源:https://stackoverflow.com/questions/50979046/angular-2-set-ngmodel-to-null-when-ngif-causes-hide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!