Search code examples
angularnestedngfor

Passing data to the child component through loop Angular


I need to pass data from array in parent component to child component and for every element in array create child component with passing data in it.

That's my parent component:

@Component({
  selector: 'app-profile-card',
  standalone: true,
  imports: [
    SkillTagComponent
  ],
  templateUrl: './profile-card.component.html',
  styleUrl: './profile-card.component.scss'
})
export class ProfileCardComponent {
  skillTypes: string[] = ['angular', 'JS', 'CSS', 'HTML']
}

Parent component template part where i try to loop and pass the data:

<div class="profile-card__tags">
    <app-skill-tag *ngFor="let skill of skillTypes"
        [skillType]="skill"></app-skill-tag>
</div>

Child component:

@Component({
  selector: 'app-skill-tag',
  standalone: true,
  imports: [
    CommonModule,
  ],
  templateUrl: './skill-tag.component.html',
  styleUrl: './skill-tag.component.scss',
})
export class SkillTagComponent {
  @Input() skillType: string = ''
}

Child component template:

<div class="skill-tag">
    {{skillType}}
</div>

So i am trying to loop through skillTypes and for every skill in it create app-skill-tag component and pass data from skill variable to app-skill-tag, but that doesn't work.


Solution

  • You have to either add the import for CommonModule or the NgFor for the for loop to start working. This module contains all the directives for looping conditionals etc. Notice that your parent is standalone, which means we have to provide all the imports for the component to work independently. The component does not need any external imports from other parts of the application and can just be imported and it'll be ready to use.

    import { CommonModule } from '@angular/common';
    ...
    
    ...
    @Component({
      selector: 'app-profile-card',
      standalone: true,
      imports: [
        SkillTagComponent,
        CommonModule,
      ],
      templateUrl: './profile-card.component.html',
      styleUrl: './profile-card.component.scss'
    })
    export class ProfileCardComponent {
      skillTypes: string[] = ['angular', 'JS', 'CSS', 'HTML']
    }