Angular 2+ - 当 ngIf 导致隐藏时将 ngModel 设置为 null [英] Angular 2+ - Set ngModel to null when ngIf causes hide

查看:24
本文介绍了Angular 2+ - 当 ngIf 导致隐藏时将 ngModel 设置为 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于 在 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 嵌套并且多个 *ngIf 会导致某些元素显示/隐藏,我想使用某种指令来完成重置.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆