Angular 2+ - Set ngModel to null when ngIf causes

2020-05-01 08:36发布

问题:

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