Shivam Gupta
Shivam Gupta

Reputation: 83

Anyway to reuse <ng-template>

My angular component looks something like this

<p-listbox>
  <ng-template let-item pTemplate="item">
    <mat-icon>find_in_page</mat-icon> {{item.name}}
  </ng-template>
</p-listbox>

<p-listbox>
  <ng-template let-item pTemplate="item">
    <mat-icon>find_in_page</mat-icon> {{item.name}}
  </ng-template>
</p-listbox>

I have two listboxes (https://www.primefaces.org/primeng/showcase/#/listbox) , each has the same template for rendering a list item. Now I have duplicate code in each of the tags.

Is there any way I can reduce code and reuse a centrally defined for the list item

Upvotes: 0

Views: 825

Answers (2)

Shivam Gupta
Shivam Gupta

Reputation: 83

The answer was simply to use a nested <ng-template>

<p-listbox>
  <ng-template let-item pTemplate="item">
    <ng-container *ngTemplateOutlet="templatePItem; context: {$implicit: item}">
    </ng-container>   
  <ng-template>
</p-listbox>

<ng-template #templatePItem let-item>
  <!-- Define your template for the item -->
  <mat-icon>find_page</mat-icon> {{item.value}}
</ng-template>

Upvotes: 1

Kinglish
Kinglish

Reputation: 23654

Well, there's the standard component route

component.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
  selector: 'app-plist-component',
  templateUrl: './plist-component.html',
  styleUrls: ['./plist-component.scss'],
})
export class PlistComponent implements OnInit {
 @Input item:any

}

component.html

<p-listbox>
  <ng-template let-item pTemplate="item">
    <mat-icon>find_in_page</mat-icon> {{item.name}}
  </ng-template>
</p-listbox>

Usage:

<app-plist-component [item]="item"></app-plist-component>

Another option. Probably not what you were after but you could loop them...

<p-listbox *ngFor="let item of [{name:'Fred'},{name:'Joe'}]">
  <ng-template let-item pTemplate="item">
    <mat-icon>find_in_page</mat-icon> {{item.name}}
  </ng-template>
</p-listbox>

Upvotes: 0

Related Questions