Search code examples
angularangular2-templateangular2-formsangular2-services

Reset ngModel values on ngIf in angular2


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


Solution

  • <input type="radio" (change)="resetForm()"/>
    
    
    resetForm(){
         if(!this.flag){
              this.collection = new Array()
         }
    }