阵列重置后垫复选框-角度

时间:2019-06-28 15:09:01

标签: angular angular-material

我试图将checked value存储在数组中,它是一个对象,因为它也包含行的数据。

component.html

<ng-container matColumnDef="actions">
  <th mat-header-cell *matHeaderCellDef> Action </th>
  <td mat-cell *matCellDef="let row; let i = index">
    <mat-checkbox (change)="$event ? selection.toggle(row) : null"
      [checked]="selection.isSelected(row)">
    </mat-checkbox>
  </td>
</ng-container>

component.ts

  close() {
    this.selectedData[this.data.myKey] = this.selection.myValue;
    this.roleOlsMap.push(this.selectedData);     // this resets back

  }

Stackblitz

1 个答案:

答案 0 :(得分:1)

每次打开对话框时,您都在使用新的选择数据创建一个新实例,并且该数据永远不会保存在对话框实例之外。您需要将选择与行数据一起保存,并在打开对话框时使用选择来初始化对话框:

<mat-checkbox (click)="$event.stopPropagation()" 
  (change)="$event ? toggleSelection(row) : null"
  [checked]="selection.isSelected(row)">
</mat-checkbox>


export class OlsComponent implements OnInit {
  constructor(@Inject(MAT_DIALOG_DATA) public data: any) {}
  listData: MatTableDataSource<any>;
  displayedColumns: string[] = ['ols', 'actions'];

  selection = new SelectionModel<any>(true, this.data.selected);

  ngOnInit() {
    this.listData = new MatTableDataSource(this.data.ols);
  }

  toggleSelection(row) {
    this.selection.toggle(row);
    this.data.selected = this.selection.selected;
  }
}