Paco Zevallos
Paco Zevallos

Reputation: 2275

*ngFor value child array

How can I repeat only the values of the recommendaciones object with *ngFor?. For example, I am now repeating the values in this way:

<div ngFor="let producto of productos">
  <div> {{ producto.titulo }} </div>
    <div>Recomendaciones: 
      <span *ngFor="let producto of productos.recomendaciones">
        {{ producto.recomendaciones }}</span>
    </div>
  </div> 
</div>

But how do I get to repeat each value of recommendaciones in an individual span?

service.ts

getProductos() {

  this.productos = [
    {
      id: 'lomoFino',
      titulo: 'Lomo fino',
      descripcion: 'Es la pieza más fina de la res, de textura tierna.',
      recomendaciones: ['Guisos', 'Freir', 'Plancha'],
      ubicacion: 'Lomo',
    },
    {
      id: 'colitaCuadril',
      titulo: 'Colita de cuadril',
      descripcion: 'Es un corte triangular y ligeramente marmoleado.',
      recomendaciones: ['Guisos', 'Freir', 'Horno'],
      ubicacion: 'Trasera',
   },
   {
     id: 'asadoCuadrado',
     titulo: 'Asado cuadrado',
     descripcion: 'Corte fibroso, de sabor agradable.',
     recomendaciones: ['Guisos', 'Freir', 'Plancha'],
     ubicacion: 'Entrepierna',
   }
]

return this.productos
}

Upvotes: 2

Views: 1685

Answers (3)

Malindu Sandaruwan
Malindu Sandaruwan

Reputation: 1517

I'm not much clear about the question. But check the following:

<div *ngFor="let producto of productos"> <!--iterate each product-->
  <div> {{ producto.titulo }} </div>
    <div>Recomendaciones: 
      <span *ngFor="let recomendacion of producto.recomendaciones"> 
<!--Iterate recomendacion of the product-->
        {{ recomendacion }}</span>
    </div>
  </div> 
</div>

Actually this is like a for loop inside a for loop (nested)

Upvotes: 2

lealceldeiro
lealceldeiro

Reputation: 14958

You need to declare a new variable recomendacion taken from producto.recomendaciones and print {{ recomendacion }} for every span.

Also fix the outer *ngFor (See docs), the * is missing. Like this:

<div *ngFor="let producto of productos">
  <div> {{ producto.titulo }} </div>
  <div>Recomendaciones:
    <span *ngFor="let recomendacion of producto.recomendaciones">
            {{ recomendacion }}</span>
  </div>
</div>
<!-- there was an additional </div> here (maybe a typo?), make sure to remove it -->

See Working Demo

Upvotes: 2

FabioG
FabioG

Reputation: 2986

you need to iterate through the recomendations of the product and print out each one of them.

<div ngFor="let producto of productos">
    <div> {{ producto.titulo }} </div>
        <div>Recomendaciones: 
            <span *ngFor="let recomendacion of producto.recomendaciones">
                {{ recomendacion  }}
            </span>
        </div>
    </div> 
</div>

Upvotes: 2

Related Questions