Search code examples
angularangular-directive

angular template to iterate over array or show single element


Some custom components are part of an angular 7 app. Following pattern is common in the components where child components expect either a single value or an array. Depending on a flag, the component renders the required layout. Following is an example:

<ng-container *ngIf="!arrayFlag">
    <app-some-component ... >
        ...
    </app-some-component>
</ng-container>
<ng-container *ngIf="arrayFlag">
  <app-some-component ...
    *ngFor="let field of fields; let i = index; trackBy:trackByFn">
        ...
  </app-some-component>
</ng-container>   

Can we simplify this pattern in such a way that the content of component need not be written twice, once for array and once for single value. e.g.

<ng-container ... >
  <app-some-component ... >
        ...
  </app-some-component>
</ng-container>  

Regards


Solution

  • If your components are "dumb" like this (they don't hold any logic, you can maybe use templates :

    <ng-template #child let-arr>
      <child-component *ngFor="let i of arr"></child-component>
    </ng-template>
    
    <ng-container *ngTemplateOutlet="child; context: { arr: flag ? [0] : myArray }"></ng-container>
    

    EDIT Done way simpler :

    <app-some-component 
      *ngFor="let field of (flag ? fields : [0]); let i = index; trackBy:trackByFn">
    </app-some-component>