10

I was going through the documentation of PrimeNG 4.3.0 for p-tree here, and came across this example where they are using a pTemplate attribute, but I am unable to understand what it does or how it works.

<p-tree [value]="files">
    <ng-template let-node pTemplate="default">
        <input [(ngModel)]="node.label" type="text" style="width:100%">
    </ng-template>
</p-tree>

Could someone please explain what the purpose of pTemplate is?

Rajat
  • 617
  • 3
  • 9
  • 16

2 Answers2

13

The only purpose of this directive is to hold ng-template reference (with some unique key assigned with it). Later inside parent component it is possible to grab the list of pTemplate directives:

@ContentChildren(PrimeTemplate) templates: QueryList<any>;

This list is a pair of string key and TemplateRef value.

This mechanism allows software developers to use multiple ng-templates and inject them to *ngTemplateOutlet directives in parent component.

<p-tree [value]="files">
    <ng-template let-node  pTemplate="picture">
        <img [attrs.src]="picture.path">
    </ng-template>
    <ng-template let-node  pTemplate="default">
        <input [(ngModel)]="node.label" type="text" style="width:100%">
    </ng-template>
</p-tree>
Karol Trybulec
  • 1,056
  • 1
  • 11
  • 17
  • 1
    If I understand this correctly, the purpose of grabbing the list of pTemplate directives is for, and perhaps limited to, reusing ng-templates? – Charley Erd Oct 14 '20 at 21:22
  • How can I see the list of pTemplate directives online? I couldn't find it – Shad Jul 28 '22 at 08:17
9

pTemplate is a custom-made directive by PrimeNG. Its purpose is to link a template defined by you (the user) to a container defined by the library (PrimeNG).

That enables the user to provide a custom template that is displayed inside a component made by the library.

The above can also be achieved using the ngTemplateOutlet directive.

You can create a component which has a ngTemplateOutlet on a <ng-container> inside it. When using that component you can place <ng-template> children between its component selector tags and give them a name. This way you essentially detach UI logic from component logic and achieve greater flexibility.

Here is a great presentation which helped me learn how to ngTemplateOutlet: https://youtu.be/2SnVxPeJdwE

Georgi
  • 91
  • 1
  • 5