0

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

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. I will try to use it.
@TechAgent done something simpler, feel free to check it out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.