Rendering an Angular Component Conditionally Using a Directive | Task

Ole Ersoy
Feb - 04  -  2 min

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

@Directive({ selector: '[isReady]' })
export class ReadyDirective implements OnInit {
  @Input('isReady') isReady: boolean;

  constructor(
    private templateRef: TemplateRef<void>,
    private vcr: ViewContainerRef
  ) {}

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

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