Search code examples
angularangular2-templateangular2-formsangular2-directives

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


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


Solution

  • 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