Displaying Element Content Conditionally With an isReady Custom Angular Directive

Ole Ersoy
Sep 2, 2022
Image by Martin Str from Pixabay

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

--

--