在 angular2 的 ngIf 上重置 ngModel 值
Reset ngModel values on ngIf in angular2
我有一个模型,它是一个数组元素。我想清除 ngIf condition.Please 上每个元素的值,在下面找到 HTML :
<div *ngIf="flag" >
<table id="table" class="table table-hover table-bordered table-mc-light-blue">
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
</tr>
</thead>
<tr *ngFor="let item of collection;">
<td>{{item.col1}}</td>
<td>
<input type="text" class="form-control" [(ngModel)]="item.col2" #input="ngModel" name="input-{{i}}">
</td>
</tr>
</table>
</div>
将 flag 设置为 false,我想清除 collection 的所有值。
有一个初始化 集合 的选项,但我不想这样做,因为我有几个这样的集合。
任何帮助将不胜感激!!
导致标志设置为 false 的 "event" 或方法调用是什么?
这是您还需要清除集合的方法调用。
像这样:
public toggleFlag() {
this.expandFlag = !this.expandFlag;
this.collection = [];
}
在你的组件中:
ngDoCheck() {
if (!this.flag) {
this.collection = [];
}
}
并且您必须像这样实施 DoCheck
:
export class myClass implements OnInit, DoCheck {
基本上,这是一个在每次发生变化时触发的侦听器,在这里我们检查 this.flag
是否为 false 并清空 collection
数组元素。
<input type="radio" (change)="resetForm()"/>
resetForm(){
if(!this.flag){
this.collection = new Array()
}
}
对于您的简单示例,如果您将 table 转换为组件,则可以使用 OnDestroy 生命周期事件清除该组件的模型值。
ngOnDestroy() {this.collection = [];}
我的情况比较复杂,所以我在
上问了一个类似的问题
我针对我的情况提出了一个解决方案,该解决方案也适用于此情况。以下项目有一个绑定到 ngModel 的指令,并使用指令的 OnDestroy 事件触发将 ngModel 设置为 null。可以修改它以将值设置为任何值,或者您可以创建一个将数组设置为空的变体。
https://stackblitz.com/edit/angular-4uwdmi?file=src%2Fapp%2Fapp.component.html
我有一个模型,它是一个数组元素。我想清除 ngIf condition.Please 上每个元素的值,在下面找到 HTML :
<div *ngIf="flag" >
<table id="table" class="table table-hover table-bordered table-mc-light-blue">
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
</tr>
</thead>
<tr *ngFor="let item of collection;">
<td>{{item.col1}}</td>
<td>
<input type="text" class="form-control" [(ngModel)]="item.col2" #input="ngModel" name="input-{{i}}">
</td>
</tr>
</table>
</div>
将 flag 设置为 false,我想清除 collection 的所有值。 有一个初始化 集合 的选项,但我不想这样做,因为我有几个这样的集合。
任何帮助将不胜感激!!
导致标志设置为 false 的 "event" 或方法调用是什么?
这是您还需要清除集合的方法调用。
像这样:
public toggleFlag() {
this.expandFlag = !this.expandFlag;
this.collection = [];
}
在你的组件中:
ngDoCheck() {
if (!this.flag) {
this.collection = [];
}
}
并且您必须像这样实施 DoCheck
:
export class myClass implements OnInit, DoCheck {
基本上,这是一个在每次发生变化时触发的侦听器,在这里我们检查 this.flag
是否为 false 并清空 collection
数组元素。
<input type="radio" (change)="resetForm()"/>
resetForm(){
if(!this.flag){
this.collection = new Array()
}
}
对于您的简单示例,如果您将 table 转换为组件,则可以使用 OnDestroy 生命周期事件清除该组件的模型值。
ngOnDestroy() {this.collection = [];}
我的情况比较复杂,所以我在
我针对我的情况提出了一个解决方案,该解决方案也适用于此情况。以下项目有一个绑定到 ngModel 的指令,并使用指令的 OnDestroy 事件触发将 ngModel 设置为 null。可以修改它以将值设置为任何值,或者您可以创建一个将数组设置为空的变体。
https://stackblitz.com/edit/angular-4uwdmi?file=src%2Fapp%2Fapp.component.html