mat-checkbox在更新Firestore /重新加载页面后继续选择

时间:2019-08-05 12:53:23

标签: angular typescript google-cloud-firestore

我正在使用mat-checkbox和ngFor从Firestore迭代数组

默认情况下,每个mat-checkbox的值都被禁用,即false。我想要的是,当选中一个或多个框并更新页面时,这些框必须保留标记,即true。有可能吗?

发生的事情是,我在每个mat-复选框中进行了总计,并且我希望页面中的任何更改都不会影响该金额。

我在Firestore中的阵列如下:

paquetes: {
  paqueteId1: {
    ...
    extras: [
      {nombre: 'nombre1', isChecked: false, costo: 10},
      {nombre: 'nombre2', isChecked: false, costo: 20},
      {nombre: 'nombre3', isChecked: false, costo: 30}
    ]
  }
  ...
}

component.html

<mat-checkbox *ngFor="let extra of paquete.extras" class="nmb" [(ngModel)]="extra.isChecked">
  {{ extra.costo}}
</mat-checkbox>

<span>{{total}}</span>

component.ts

get total() {
  return this.paquete.extras.filter(x => x.isChecked).reduce((a, b) => a + b.costo + 0, 0) * this.numeroPersonas + this.subtotal;
}

this.fs.getPaquete(this.idPaquete).subscribe( res => {
   this.paquete = res.data();
  }
);

1 个答案:

答案 0 :(得分:0)

在将响应数据分配给 paquete subscription 内的 getPaquete 之前,您必须执行一些操作strong>函数可保持检查值不变。请执行以下操作。

this.fs.getPaquete(this.idPaquete)
  .subscribe( (res: any) => {

    const paquete = res.data();
    const selected = this.paquete.extras.filter(x => x.isChecked);

    selected.forEach(y => {

      const found = paquete.extras.find(z => z.nombre === y.nombre);
      const index = paquete.extras.indexOf(found);

      if (index > -1) {
        paquete.extras[index].isChecked = true;
      }
    });
    this.paquete = paquete;
}

希望这会对您有所帮助。接受任何查询。