Reset ngModel values on ngIf in angular2

*爱你&永不变心* 提交于 2019-12-11 08:08:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!