*ngFor on elements of ng-content Angular

3.1k views Asked by At

I was wondering if is it possible to create a iteration of certain elements of . I need a different css class to every element of the ng-content so i need to make a loop of every element of ng-content. Is it possible?

Right now i pass a parameter to the child element to enumerate him, but i would like to do it without the number. This is my code:

<sys-tab [tabs]="['Principal', 'Complementar']">
  <sys-tab-content [num]="1">
    <sys-panel header="Dados Gerais">
      <sys-input-text header="Nome" tam="1"></sys-input-text>

      <sys-input-mask header="CNPJ"></sys-input-mask>
      <sys-input-mask header="CNES"></sys-input-mask>
      <sys-input-mask header="Telefone"></sys-input-mask>

      <sys-input-text header="Email"></sys-input-text>
    </sys-panel>
  </sys-tab-content>
  <sys-tab-content [num]="2">
    <sys-input-text header="Email"></sys-input-text>
  </sys-tab-content>
</sys-tab>

As you can see, to the child i passs the number so i can recognize who is him, but i want to create a loop to the ng-coontent so i can add a different class to every "sys-tab-content"

2

There are 2 answers

0
Hely Saul Oberto On BEST ANSWER

There's two ways of adding a "ngFor" or iterate trough the childs.

One is by transclusion: and the other one is by checking the ViewChildren of the parent component.

0
Neo On

Simple List Example with dynamic ngTemplate

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent  {
  items = [ { name: 'abc' }, { name: 'cdf' }, { name: 'fgh' } ];
}

app.component.html

<nu-list [itemTpl]="itemTpl" [items]="items"></nu-list>
<ng-template let-item #itemTpl> 
    <h1>{{item.name}}</h1>
</ng-template>

list.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'nu-list',
  templateUrl: './list.component.html'
})
export class ListComponent  {

  @Input() itemTpl;
  @Input() items;

}

list.component.html

<ng-container *ngFor="let item of items">
  <ng-container *ngTemplateOutlet="itemTpl; context: {$implicit: item}"></ng-container>
</ng-container>

Example Link: https://stackblitz.com/edit/angular-list-ngtemplateoutlet