Displaying Element Content Conditionally With an isReady Custom Angular Directive | Task

Ole Ersoy
Aug - 02  -  2 min

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.

@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);
    }
  }
}

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

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

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

Demo