【问题标题】:mat-checkbox keep selecting after updating firestore / reload pagemat-checkbox 在更新 firestore / reload 页面后继续选择
【发布时间】:2019-08-05 12:53:23
【问题描述】:

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

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

发生的情况是,我正在对每个 mat-checkbox 进行总和,并且我希望页面中的任何更改都不会影响该总和。

我在 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();
  }
);

【问题讨论】:

  • 您可以将 [(ngModel)]="extra.isChecked" 更改为 [ngModel]="extra.isChecked" 。这不会检测到组件的变化,您的总和不会受到影响
  • 没用,很抱歉。检测组件的变化。
  • 你能展示一下你的 this.paquete 数组是什么样子的吗?
  • 您似乎没有将任何内容写回数据库。您必须使用用户所做的更改来更新 firestore 数据库。如果您不更新数据库,您将始终在页面重新加载时从数据库中加载相同的数据。

标签: angular typescript google-cloud-firestore


【解决方案1】:

您必须在 getPaquete 函数的 subscription 内将响应数据分配给 paquete 之前执行一些操作以保持检查价值,因为它是。请按以下步骤操作。

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

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

【讨论】:

  • 抱歉,当我尝试 const selected = package.extras.filter (x =&gt; x.isChecked); 时,我收到错误:TypeError: Cannot read property 'extras' of undefined 的行:const selected = this.package.extras.filter (x =&gt; x.isChecked); 一切都保持不变。
  • 不是package应该是paquete
  • 还有一件事要确保 res.data() 提供的数据类似于您的示例数据数组
猜你喜欢
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
相关资源
最近更新 更多