Displaying Element Content Conditionally With an isReady Custom Angular Directive

Scenario

We wish to display an elements content only after after some application state is ready.

<h1><code>isReady</code> set to <code>true</code></h1>
<div>
<p *isReady="true">Content</p>
</div>
<h1><code>isReady</code> set to <code>false</code></h1>
<div >
<p *isReady="false">Content</p>
</div>

We could have easily done this with *ngIf , but this approach can be adapted to more specific use cases, such as only displaying content when a certain language is being rendered.

Approach

We will create the directive like this.

Note that the content contained within the element that the directive is attached to is passed in via the constructor TemplateRef<void> argument.

If the directive is truthy we insert the content with the ViewContainerRef.createEmbeddedView call.

if (this.isReady) {
this.vcr.createEmbeddedView(this.templateRef);
}

Demo

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ole Ersoy

Ole Ersoy

Founder of Firefly Semantics Corporation