Search code examples
javascriptangularloopsngfor

Angular nester ngFor, get value from parent loop?


I have a nested ngFor loop which uses nested json, for example

<mat-tab *ngFor="let car of cars">

    <car-component *ngFor="let model of car.models" [name]="model.name" [color]="model.color">
    </car-component>

</mat-tab>

Where the data might be

  {
    name: 'vw',
    models: [
     {name: 'beetle', color: 'red'}
     {name: 'jetta', color 'blue'
    ]
  },
  {
    name: 'bmw',
    models: [
     {name: 'x5', color: 'silver'}
     {name: 'm3', color 'blue'
    ]
  }

the car-component shows the car image and company logo.

I have the images organized my manufacturer, such as

vw--|
    |logo.png
    |jetta.png
    |beetle.png
bmw-|
    |logo.png
    |x5.png
    |m3.png

So, the image path in my nested component is /assets/images/{{manufacturer}}/{{name}}.png

So I need to pass the manufacturer, which is in the outside loop as the name property.

I could repeat the manufacturer in the json for each model, but is there a way to retrieve the name property of the parent ngFor iteration?


Solution

  • you can access it inside loop everywhere (nested) cars.name in you case BMV or vw