user007
user007

Reputation: 199

Loading mat accordion dynamically

Based on the JSON structure, I wanted to render the accordion. Below is how it looks like.

const area = [{
  type: 'column',
  text: ''
}, {
  type: 'accordion-item',
  text: 'accordion-item 1'
},
{
  type: 'accordion-item',
  text: 'accordion-item 2'
},
{
  type: 'accordion-item',
  text: 'accordion-item 3'
},
{
  type: 'column',
  text: ''
}]

So my component html looks like this,

 <ng-container *ngFor="let area of areas">
  <ng-container *ngIf="area.type === 'accordion-item'; else section">
    <mat-accordion>
      <accordion-item [item]="area"></accordion-item>
    </mat-accordion>
  </ng-container>
  <ng-template #section></ng-template>
</ng-container>

Accordion Item component

<mat-expansion-panel>
    <mat-expansion-panel-header>
        <mat-panel-title>
             {{title}}
        </mat-panel-title>
    </mat-expansion-panel-header>
</mat-expansion-panel>

I could able to load the accordion component. But the issue is native functionality is not working as expected .

Because for each accordion-item I loading this tag <mat-accordion> again n again.

So How to avoid this ? Please help


Update.

After implementing the solution, my template looks like this

<mat-accordion>
  <ng-container *ngFor="let area of areas" *ngTemplateOutlet="section; context:area">
    <accordion-item *ngIf="area.type === 'accordion-item'; else section" [item]="area">
    </accordion-item>
  </ng-container>
</mat-accordion>

<ng-template #section let-name="name">
  <area-template [area]="area" class="{{ area.type }}">
  </area-template>
</ng-template>

It's throwing template phase error. please help

Upvotes: 0

Views: 2213

Answers (1)

Luis Rico
Luis Rico

Reputation: 635

<mat-accordion>
   <ng-container *ngFor="let area of areas" >
      <accordion-item *ngIf="area.type === 'accordion-item'"  [item]="area"></accordion-item>
   </ng-container>
</mat-accordion>

<ng-container *ngFor="let area of areas" #section>
   <ng-container *ngIf="!area.type === 'accordion-item'" #section>
      YOUR TEMPLATE
   </ng-container >
</ng-container >

Upvotes: 1

Related Questions