array resets back mat checkbox - angular

百般思念 提交于 2020-01-06 06:44:52

问题


i am trying to store the checked value in an array, it is an object since it also consists data for the row.

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:


Each time you open the dialog you are creating a new instance with new selection data, and this data is never saved outside the dialog instance. You need to save the selections with the row data and initialize the dialog with the selection when it is opened:

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


来源:https://stackoverflow.com/questions/56809286/array-resets-back-mat-checkbox-angular

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