G
G
GF2020-10-31 22:52:27
JavaScript
GF, 2020-10-31 22:52:27

Angular recursive component with custom templates. How to create?

Good evening gentlemen. I'm trying to make a recursive component, but so that you can set any view for data through ngTemplateOutlet. Tell me how to do it better? Now the problem is to pass the template inside the component.
example https://stackblitz.com/edit/angular-render-recursi...
only here the template is hardcoded.
API will be like this (if possible)

//  recursive-view.component.ts
export class RecursiveViewComponent<T> {
  @Input() value: RecursiveArray<T> = []
  @ContentChild('templateRef') templateRef: TemplateRef<unknown>
}

// recursive-view.component.html
<ng-container *ngIf="isArray; else itemView">
  <app-recursive-view *ngFor="let item of value" [value]="item">
     <!-- Вот здесь должен быть ng-template как снаружи чтобы рекурсия продолжалась :|  -->
  </app-recursive-view>
</ng-container>

<ng-template #itemView>
  <ng-container *ngTemplateOutlet="templateRef; context: {$implicit: value}"></ng-container>
</ng-template>

// app.component.html
<app-recursive-view [value]="value">
  <ng-template #templateRef let-data>
    <h1>{{data.name}}</h1>
    <h3>{{data.text}}</h3>
    <h5>{{data.likes}}</h5>
  </ng-template>
</app-recursive-view>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question