首页 > 解决方案 > 如何强制 ngFor 渲染

问题描述

我从firebase读取对象数组,然后检查是否有任何重复并计算重复的数量。之后,我创建了一个新对象,它显示了重复项的数量及其名称。

我从firebase读取的数据:

a {
  name: "sweet potato",
  color: "orange"
}
b {
  name: "sweet potato",
  color: "orange"
}
c {
  name: "eggplant",
  color: "purple"
}

过滤后的数据:

a {
  name: "potato",
  count: 2
}
b {
  name: "eggplant",
  count: 1
}

打字稿代码:

constructor(private firebaseService:FirebaseService) { }

ngOnInit() {
  this.firebaseService.getData("/name").subscribe(name => {
    this.names=name;
    this.updateMain();
  }) 
}

duplicateFilter() {       // Here we Detect Duplicate
  this.total = [];
  var newArr = [],
      origLen = this.names.length,
      found, x, y;

  for (x = 0; x < origLen; x++) {
    found = undefined;
    for (y = 0; y < newArr.length; y++) {
      if (this.names[x].name === newArr[y]) {
        found = true;
        break;
      }
    }
    if (!found) {
      newArr.push(this.names[x].name);
    }
  }
  return newArr;
}

elementFilter(food) {
  for (var num = 0, i = 0; i < this.names.length; i++) {
    if (this.names[i].name == food) {
      num = num + 1;
    }
  }
  this.total.push(num);
}

objectCreate() {
  this.modal = [];
  for(var i = 0; i < this.newArr.length; i++) {
    this.modal.push({
      name: this.newArr[i],
      count: this.total[i],
    })
  }
}

updateMain() {
  this.newArr = this.duplicateFilter();

  for (let i in this.newArr) {
    this.elementFilter(this.newArr[i]);
  }
  this.objectCreate();
}

HTML 代码:

<div *ngFor="let modal of modal>
  <div class="center">{{modal.name}}</div>
  <div class="center">{{modal.count}}</div>
</div>

问题是信息不会因任何更改(添加或编辑)而更新,即使我发送更新过滤的对象也是如此。它只是显示相同的信息。我可以强制 ngFor 以其他方式渲染吗?

标签: angularfirebase

解决方案


您没有定义新变量。尝试<div *ngFor="let m of modal>,或者更可取<div *ngFor="let modal of modals>的是,将变量的名称更新为modals.


推荐阅读