Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass context to Angular 5 template from *ngIf

Angular's NgTemplateOutlet allows you to pass a context to the outlet for property binding.

<ng-container *ngTemplateOutlet="eng; context: {$implicit: 'World'}"></ng-container>
<ng-template #eng let-name><span>Hello {{name}}!</span></ng-template>

Angular's *ngIf allows you to embed one template or another based on a boolean condition:

<ng-container *ngIf="isConditionTrue; then one else two"></ng-container>
<ng-template #one>This shows when condition is true</ng-template>
<ng-template #two>This shows when condition is false</ng-template>

How can I pass context to these templates referred to within the *ngIf syntax?

like image 989
BeetleJuice Avatar asked Feb 15 '18 15:02

BeetleJuice


People also ask

Can I use NG content in ng-template?

To sum up, ng-content is used to display children in a template, ng-container is used as a non-rendered container to avoid having to add a span or a div, and ng-template allows you to group some content that is not rendered directly but can be used in other places of your template or you code.

How do you use async pipe with NgIf?

Use the async pipe with ngIfThe condition (obsValue | async) becomes true , when the observable returns a value. Until then the elseBlock is shown, which we use to display the loading indicator. In the example, it displays the message Observable is loading.

What is $implicit in Angular?

You can define local variables on ng-template through let-name. When angular creates a template by calling createEmbeddedView it can also pass context that will be used inside ng-template. Using the key $implicit in the context object will set its value as default.

What is difference between ng-container and ng-template?

ng-container serves as a container for elements which can also accept structural directives but is not rendered to the DOM, while ng-template allows you to create template content that is not rendered until you specifically (conditionally or directly) add it to the DOM.


1 Answers

Actually you can input your condition into ngTemplateOutlet (and get rid of ngIf).

<ng-container *ngTemplateOutlet="condition ? template1 : template2; context: {$implicit: 'World'}">
</ng-container>
like image 132
Sielu Avatar answered Oct 11 '22 15:10

Sielu