【问题标题】:array resets back mat checkbox - angular阵列重置回垫复选框 - 角度
【发布时间】:2019-06-29 02:17:42
【问题描述】:

我正在尝试将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>

组件.ts

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

  }

Stackblitz

【问题讨论】:

    标签: angular angular-material


    【解决方案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;
      }
    }
    

    【讨论】:

    • 这行得通,一个简单的问题,roleOlsMap 数组,为什么在我关闭对话框后它会被重置。
    • 正如我所说,每次打开对话框时都会重新实例化它。该数组不是“重置”的,当您关闭对话框时它会被丢弃。您没有在任何地方保存该数据,因此只要对话框实例存在,它就存在。
    • 您好,这个解决方案有个小问题,我一次只能选择一个复选框。
    • 不同的问题。这是因为您的选择模型有多个 == false。然后你还需要更改 this.data.selected。查看更新的代码。
    • 在此之前我从未使用过它。也许看到jtrussell.io/angular-selection-model
    猜你喜欢
    • 2018-03-31
    • 1970-01-01
    • 2018-05-03
    • 2020-02-06
    • 1970-01-01
    • 2021-02-09
    • 2018-08-21
    • 2019-05-27
    • 2019-11-08
    相关资源
    最近更新 更多