在 mat-table 中加载初始值时未选中复选框

Checkbox are not checked when initial values are loaded in a mat-table

想要加载一个 table 复选框,该复选框已使用来自本地存储变量的初始值进行了检查。我已经将初始数据放入 selectionModel:

this.servChecked = [
    {tipo: 'Servicio', descripcion: 'Visit', cantidad: '1', codsrv: '11123'},
    {tipo: 'Equipo', descripcion: 'RPV', cantidad:'1', codsrv: '11124'}
  ];

this.selection = new SelectionModel<ServiciosAdicionales>(true, this.servChecked);

It does load the array in the selection.selected but the checkboxs are not checked.

TS:

 this.servChecked = JSON.parse(localStorage.getItem("servAdicionales"));
    this.infoCompleta = JSON.parse(localStorage.getItem("infoParaServiciosAdicionales"));
    this.tipoServicio = this.route.snapshot.paramMap.get("tipoServicio");

    let listEquipos = [];
    let listServicios = [];
    this.datosServicios.forEach(element => {
      switch(element.tipo) {
        case '1':
          element.tipo = 'Servicio'
          listServicios.push(element);
          break;
        case '2':
          element.tipo = 'Equipo'
          listEquipos.push(element);
          break;
      }
    });

    this.dataSource = new MatTableDataSource<ServiciosAdicionales>(this.datosServicios);
    this.dataSourceEquipo = new MatTableDataSource<ServiciosAdicionales>(listEquipos);
    this.dataSourceServicio = new MatTableDataSource<ServiciosAdicionales>(listServicios);

    this.selection = new SelectionModel<ServiciosAdicionales>(true, this.servChecked);

我希望在加载初始值时选中复选框。

您试图推入 selection 模型的对象来自数组 dataosServicios。但是 selection 模型寻找将在 table 中渲染的对象。这将是与数组不同的实际行对象。

初始化dataSource后,试试下面的代码:

this.selection = new SelectionModel<ServiciosAdicionales>(true, this.dataSourceEquipo.data[0]);

上面的代码将select排在table的第一行。

要回答您的问题,请从 localStorage 获取数据,然后为 table 创建数据源。将对象从 localStorage 映射到 dataSource.data,然后将 dataSource.data 个对象添加到 selectionModel 数组。