手动触发ngFor或使其正确更新DOM

问题描述 投票:0回答:1

我有此代码

TS

modal.onDidDismiss().then(res => {
  if (res.data !== undefined) {
    this.foodAllergies.push(res.data)
    if (this.categories.length === 0) {
      this.categories.push(res.data.category)
    } else {
      if (!this.categories.includes(res.data.category)) {
        this.categories.push(res.data.category)
      }
    }
  }
});

HTML

<ion-grid>
    <ion-row *ngFor="let category of categories">
      <ion-col>
        <h3>{{category}}</h3>
        <ion-list>
          <ion-item *ngFor="let food of foodAllergies | categoryFilter: category">
            <ion-label>{{food.name}}</ion-label>
          </ion-item>
        </ion-list>
      </ion-col>
    </ion-row>
  </ion-grid>

因此,只要我将新类别添加到类别数组,视图就会正确更新,以显示该类别中的食物问题是,当我添加一个已经在Categories数组中存在的类别时,该视图不会正确更新,因为第二个ngFor不会触发它不会添加具有该类别的食物

我该如何解决这个问题?

angular ionic-framework ionic4 ngfor
1个回答
0
投票

您的if() { ... } else { if() { ... } }在做同样的事情,我觉得很奇怪。

尝试以foodAllergies方式更新immutable(更改其参考),看是否有帮助并开始进行变更检测。

modal.onDidDismiss().then(res => {
  if (res.data !== undefined) {
    this.foodAllergies = [...this.foodAllergies.map(foodAllergy => ({...foodAllergy})), res.data];
    this.foodAllergies.push(res.data);
    // you can keep your if and else if but I have removed them here for this example
    this.categories.push(res.data.category);
   }
  }
});

对于...this.foodAllergies.map(foodAllergy => ({...foodAllergy})),取决于foodAllergy中有多少个深层嵌套的对象/数组,您必须一成不变地复制它们。

因此,如果foodAllergy看起来像{ name: 'Peanuts', x: [1, 2, 3], y: { a: 1, b: 2 } },它将变成:

...this.foodAllergies.map(foodAllergy => ({
                                            ...foodAllergy, 
                                            x: [...foodAllergy.x], 
                                            y: {... foodAllergy.y } 
                           }))
© www.soinside.com 2019 - 2024. All rights reserved.