Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ng-template is not working in Angular?

Tags:

angular

We can't use *ngFor and *ngIf on the same element. A technique is to nest them. Almost everywhere it's OK, except in tables when we want to both loop over tr and print them conditionally.

As suggested here we should use <template>, or <ng-template> elements, so that it won't be printed to the DOM.

But I can't make it work. It simply doesn't print out anything. Here's a plunker to show it in action.

What should I do?

like image 504
mohammad rostami siahgeli Avatar asked Nov 30 '22 14:11

mohammad rostami siahgeli


2 Answers

As *ngIf is rendered as [ngIf], try using [ngIf] directly on template it should work.

When we prepend a directive with * we are telling it to use the element it’s attached to as the template. Basically *ngIf is a combo of ng-template + [ng-If].

Html:

<tr *ngFor="let item of items">
   <ng-template [ngIf]="item.month == 12">
        <td>{{ item.year }}</td>
        <td>{{ item.month }}</td>
   </ng-template>
</tr>

or simply you can decorate with *ngIf

<tr *ngFor="let item of items">
   <div ngIf*="item.month == 12">
        <td>{{ item.year }}</td>
        <td>{{ item.month }}</td>
   </div>
</tr>

updated plunker

Useful article on Structural directives

like image 55
super cool Avatar answered Dec 04 '22 02:12

super cool


so there is something call ng-container also,

ng-container and ng-template Both of them are at the moment (2.x, 4.x) used to group elements together without having to introduce another element which will be rendered on the page (such as div or span).

the difference between ng-template and ng-container is

ng-template is used for a structural directive like ng-if, ng-for and ng-switch. If you use it without the structural directive, nothing happens and renders.

ng-container is used when you don't have a suitable wrapper or parent container. In most cases, we are using div or span as a container but in such cases when you want to use multiple structural directives, but you can't use more than one structural directive on an element, in that case, ng-container can be used as a container

in your case

<ng-template> is used to declare a template. What you want here is to hide/display some nodes

so you need to use ng-container for the same like

<tr *ngFor="let item of items">
    <ng-container *ngIf="item.month == 12">
        <td>{{ item.year }}</td>
        <td>{{ item.month }}</td>
    </ng-container>
</tr>

there are couple of links which will help you to understand the both

related link

structural directives

discussion on ng-template and ng-container

like image 29
Hrishikesh Kale Avatar answered Dec 04 '22 04:12

Hrishikesh Kale