Liero
Liero

Reputation: 27338

Does placing ng-template inside *ngFor affect performance at all?

Let's assume following ItemComponent that is created many times:

<li *ngFor="let item of items">
    <app-item [data]="item"></app-item>
</li>

and contains buttons that on click display some complex modal dialogs .

Does it affect performance of the app (e.g. startup time, or memory footprint), when I place some ng-templates of the dialogs inside the ItemComponent, or outside the *ngFor?

I mean, I know the templates are not instantiated until the dialogs are invoked, but I'm not sure if the template itself is created once per component, or once per instance?

Upvotes: 4

Views: 1481

Answers (1)

Reactgular
Reactgular

Reputation: 54771

Does it affect performance of the app (e.g. startup time, or memory footprint), when I place some ng-templates of the dialogs inside the ItemComponent, or outside the *ngFor?

<ng-template> is a component that will be created. The component creates a template reference from it's inner DOM elements, and those DOM elements are not rendered on the page. The template remains in memory for each item created in the ngFor. ngTemplate has a current context and an injected context. The value of item will be present in the current context when it is inside ngFor and must be provided in the context object when using ngTemplateOutlet.

It is a better practice to keep ngTemplate outside of ngFor and pass item as part of the context when using ngTemplateOutlet.

Here's a tutorial that helps explain things better.

https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/

Upvotes: 2

Related Questions