Search code examples
angulartypescriptangular-ngmodelngfor

Is there a way to use ngModel and NgFor together?


I would like to reset the values of checkboxes when user clicks on button "cancel". Is there a way I could use ngFor and NgModel together so that the values would reset? I'm trying to set the object that *ngFor uses to an earlier version.

HTML

   <div *ngFor="let object of objects">
            <input [(ngModel)]="object.isSelected" type="checkbox"> 
   </div>

   <button type="button" (click)="cancel()">Cancel</button>

TypeScript

cancel(){
   this.object = this.unChangedObject;
}

The values do reset, but how could I show the changes to the user?


Solution

  • Deep copy your object to another variable using Object.assign and assign it in the cancel function

    constructor(){
      this.unChangedObject = Object.assign({},this.object  )
    }
    
    cancel(){
       this.object = this.unChangedObject;
    }