Rendering an Angular Component Conditionally Using a Directive

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

--

--

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