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.
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.
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> ).
In Angular, we cannot use two structural directives on the same element. i.e., we cannot place *ngFor,*ngIf together on same element.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With