Angular 2+-在ngIf导致隐藏时将ngModel设置为null [英] Angular 2+ - Set ngModel to null when ngIf causes hide
问题描述
我遇到的问题类似于在angular2中的ngIf上重置ngModel值
每当父级* ngIf导致该元素被隐藏时,我想将任何ngModel值设置为null.
I would like to set any ngModel values to null whenever a parent *ngIf causes that element to be hidden.
如果我的情况很简单,我不会问这个.如果真是这样,那么我只是对* ngIf值的更改进行重置,但是由于我的表单具有多个* ngIf嵌套级别,并且多个* ngIfs可以导致某些元素显示/隐藏,所以我想使用某种指令来完成重置.
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.
我不想将所有简单的输入元素转换为组件以利用OnDestroy事件,因此在执行此操作之前,我想看看是否还有其他方法.
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.
我已经创建了一个StackBlitz项目来说明我想做的事情.在此项目中,有没有一种方法可以实现(ngOnDestroy)事件?
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
推荐答案
我想出了一个解决方案.以下项目具有绑定到ngModel的指令,并使用该指令的OnDestroy事件触发将ngModel设置为null.
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
这篇关于Angular 2+-在ngIf导致隐藏时将ngModel设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!