ngFor does not give the expected result

0

My ngFor is not showing all the data that arrives, but in the console it shows all the results.

I get some data from the API and it has a sales data and a meta data, they come in an array and I use the forEach in them, and if it hits the target it should go to another array:

this.MetaService.FiliaisMetaDiarias().subscribe(
  data => {
    const response = (data as any)
    this.objeto_retorno = JSON.parse(response._body);

    this.objeto_retorno.forEach(element => {

      this.tots = element.TOTAL
      if (this.tots >= this.MetaAtingida) {

        this.fil = [
          {
            FI: element.FILIAL,
            porc: element.TOTAL
          }
        ]

        this.fil.forEach(elements => {
          this.mainColor = 'MetaAtingida'
        })

      }

Then I play html:

<p [class]="mainColor + ' teste'" *ngFor="let elements of fil" >Filial {{ elements.FI }} = {{ elements.porc }}</p>

It should show all results, but for some reason is showing only the last data, but in the console it shows all the data.

Can anyone help me?

    
asked by anonymous 16.08.2018 / 18:12

2 answers

2

The error is here:

this.fil = [
          {
            FI: element.FILIAL,
            porc: element.TOTAL
          }
        ]

You are reinitializing this.fil to each iteration of forEach , which means that it will always have only the current iteration element, in the case of the last one, the last element of the collection.

The correct would be to initialize this.fil out of the loop, and fill with .push in the iteration:

this.fil = [];
this.objeto_retorno.forEach(element => {
    this.fil.push({
        FI: element.FILIAL,
        porc: element.TOTAL
    });
 // resto do código...
});
    
16.08.2018 / 18:27
2

You are defining the structure of the this.fil all forEach iteration.

For example, I'll assume that objeto._retorno looks like this:

objeto [
   _retorno [
      { "FILIAL": "filial1",
        "porc": "porc1",
        "total": total1 },
      { "FILIAL": "filial2",
        "porc": "porc2",
        "total": total2 }
   ]
]

If the value of the element's "total" property is greater than the target reached, you mark the value of the element a fil.

Then, in the first element, fil would have this value:

fil [
   FI: "filial1",
   porc: "porc1"
]

But in the second, fil will be flagged again, so it looks like this:

fil [
   FI: "filial2",
   porc: "porc2"
]

What you should do is insert into fil, do not mark the value of the object to fil. Something like this.fil.append() should resolve in this case.

    
16.08.2018 / 18:25