问题
I have a model which is an array element. I want to clear the values of each element on ngIf condition.Please find below 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>
On flag set to false, I want to clear all values of the collection. There is an option of initializing collection, but I don't want to do that as I have several such collections.
Any help would be appreciable!!
回答1:
<input type="radio" (change)="resetForm()"/>
resetForm(){
if(!this.flag){
this.collection = new Array()
}
}
回答2:
What is the "event" or method call that causes the flag to be set to false?
This is the method call where you'll also want to clear the collection.
Something like this:
public toggleFlag() {
this.expandFlag = !this.expandFlag;
this.collection = [];
}
回答3:
In your component:
ngDoCheck() {
if (!this.flag) {
this.collection = [];
}
}
And you have to implement DoCheck
like this:
export class myClass implements OnInit, DoCheck {
Basically, this is a listener that trigger at every change that happens, and here we check that this.flag
is false and we empty the collection
array element.
回答4:
For your simple example, if you convert your table into a component, then you can use the OnDestroy lifecycle event to clear the model values for that component.
ngOnDestroy() {this.collection = [];}
I have a situation where it's more complicated, so I've asked a similar question at Angular 2+ - Set ngModel to null when ngIf causes hide
回答5:
I came up with a solution for my situation that would also work for this one. 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. It could be modified to set the value to anything or you could create a variation that would set arrays to empty.
https://stackblitz.com/edit/angular-4uwdmi?file=src%2Fapp%2Fapp.component.html
来源:https://stackoverflow.com/questions/43658117/reset-ngmodel-values-on-ngif-in-angular2