Rendering an Angular Component Conditionally Using a Directive

Ole Ersoy
Sep 2, 2022

--

Image by Peter Dargatz from Pixabay

Scenario

If the *isReady directive is is set to false , then we want to render a SpinnerComponent , otherwise we want to show the content contained within the element that the directive is declared on.

<h1><code>isReady</code> set to <code>true</code></h1>
<div *isReady="true">Content</div>
<h1><code>isReady</code> set to <code>false</code></h1>
<div *isReady="false">
<span>Display the spinner component instead of this span</span>
</div>

Approach

If the directives isReady property is truthy we render the content ( The content is captured in the TemplateRef and we call this.vcr.createEmbeddedView(this.templateRef) to render it).

If the isReady value is false, we render the SpinnerComponent like this.

if (!this.isReady) {
this.vcr.createComponent(SpinnerComponent);
}

Demo

--

--

Ole Ersoy
Ole Ersoy

Written by Ole Ersoy

Founder of Firefly Semantics Corporation

No responses yet