Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - ng-template with parameter inside ngIf inside ngFor [duplicate]

I am trying to build this template:

<ul>     <li *ngFor='let link of links'>         <ng-container *ngIf="link.type == 'complex'; then complexLink else simpleLink"></ng-container>     </li> </ul>  <ng-template #simpleLink>     ...     {{ link.some_property }} </ng-template>  <ng-template #complexLink>     ...     {{ link.some_property }} </ng-template> 

The problem is that the link variable is undefined inside the ng-template so I get an error of accessing 'some_property' of undefined.

I am struggeling to understand how I pass the link variable from the ngFor to the ng-template

It would be great to know if there are multiple solutions for this problem.

like image 744
yanivps Avatar asked Jan 30 '18 06:01

yanivps


People also ask

Can we use ngIf and ngFor together in Angular?

In angularjs (angularjs is first version of angular) we can use both on same element but not in angular 2 because Angular unable to decide which one to use first for example if we are using ngIf and ngFor together. In the above example, if angular try to execute first ngIf then place is undefined for it.

Can we use ngFor in ng-template?

When we use *ngFor , we're telling Angular to essentially treat the element the * is bound to as a template. Angular's <ng-template> element is not a true Web Component (unlike <template> ).

Can ngFor and ngIf be used together on the same UI element or component?

In Angular, we cannot use two structural directives on the same element. i.e., we cannot place *ngFor,*ngIf together on same element.

Can we apply ngIf to ng-template?

the element onto which the structural directive ngIf was applied has been moved into an ng-template. The expression of *ngIf has been split up and applied to two separate directives, using the [ngIf] and [ngIfElse] template input variable syntax.


Video Answer


1 Answers

You can do it like :

<ul>     <li *ngFor='let link of links'>         <ng-container               [ngTemplateOutlet]="link.type == 'complex' ?complexLink : simpleLink"               [ngTemplateOutletContext]="{link:link}">         </ng-container>     </li> </ul>  <ng-template #simpleLink let-link='link'>     Simple : {{ link.name }} </ng-template>  <ng-template #complexLink let-link='link'>     Complex : {{ link.name }} </ng-template> 

WORKING DEMO

like image 118
Vivek Doshi Avatar answered Sep 19 '22 11:09

Vivek Doshi