首页 文章

有没有办法一起使用ngModel和NgFor?

提问于
浏览
1

我想在用户点击按钮"cancel"时重置复选框的值 . 有没有办法我可以一起使用ngFor和NgModel,以便重置值?我正在尝试将 *ngFor 使用的对象设置为早期版本 .

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;
}

这些值会重置,但我怎样才能显示对用户的更改?

2 回答

  • 0

    使用 Object.assign 将对象深度复制到另一个变量,并在取消函数中指定它

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

    你可以用另一种方式来看待它 . 仅在提交时更新 . 为此,您可以在 *ngFor 上使用管道,该管道返回复制对象的数组 . 此解决方案仅适用于浅层对象,但您也可以尝试查找一些深层复制方法(下面未经测试的代码):

    pipe

    @Pipe({
      name: 'copyArr'
    })
    export class CopyArrPipe implements PipeTransform {
      public transform(arr: object[] = []): object[] {
        return arr.map(obj => ({...obj}));
      }
    }
    

    template

    <ng-container *ngIf="objects | copyArr as objectsCopy">
    
      <div *ngFor="let object of objectsCopy">
        <input [(ngModel)]="object.isSelected" type="checkbox"> 
      </div>
    
      <button type="button" (click)="cancel()">Cancel</button>
      <button type="button" (click)="commit(objectsCopy)">Commit</button>
    </ng-container>
    

    component

    @Component({...})
    export class FooBarComponent {
    
      objects = [];
    
      cancel(){
        this.objects = [...this.objects];
      }
    
      commit(newObjects) {
        this.objects = newObjects;
      }
    }
    

相关问题