Search code examples
javascriptarraysangularnested-loopsngfor

Angular 7 nested for using parent value as index for child


Is it possible to do this in Angular 2+?

let's say I have the following objects:

 myParent = [{id: 1, code: 'code1', title: 'parentTitle1'}, {id: 2, code: 'code2', title: 'parentTitle2'}];
 myChild = {code1: [{id: 1, title: 'childTitle1'}, {id: 2, title: 'childTitle2'}], code2: [{id: 4, title: 'childTitle1'}]

I wanna Iterate the first one and then display the items of the second one, using the 'code' value of the parent object as index:

<h3 *ngFor="let parent of myParent">{{parent .title}} 
  <br>
  <span *ngFor="let child of myChild[parent.code]"> {{child.title}} </span>
  <br>
</h3>

I'm not getting any error on the console, but the child 'for' is not displaying anything. I used to do this on AngularJS but not sure if it's possible to do it in NG7


Solution

  • Check this stackblitz. Is this not working for you?

    I tried with these data:

      myParent = [{id: 1, code: 'code1', title: 'parentTitle1'}, {id: 2, code: 'code2', title: 'parentTitle2'}];
     myChild = {code1: [{id: 1, title: 'childTitle1'}, {id: 2, title: 'childTitle2'}], code2: [{id: 4, title: 'childTitle1'}]};
    

    And the html

    <h3 *ngFor="let parent of myParent">{{parent .title}} 
      <br>
      <span *ngFor="let child of myChild[parent.code]"> {{child.title}} </span>
      <br>
    
    </h3>
    

    The stackblitz is working as you intended. Can you share some more code, as it seems like the data might not match.