Advertisement
Advanced Angular, Directives

How would you build a custom structural directive similar to ngIf from scratch?

Short answer

You inject a TemplateRef, representing the content the directive is applied to, and a ViewContainerRef, representing where that content can be inserted, then use createEmbeddedView and clear methods to add or remove the template's content based on your own custom condition.

Save Angular mock interview
Advertisement
AModel answer
You inject a TemplateRef, representing the content the directive is applied to, and a ViewContainerRef, representing where that content can be inserted, then use createEmbeddedView and clear methods to add or remove the template's content based on your own custom condition.
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({ selector: '[appUnless]', standalone: true })
export class UnlessDirective {
  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}

  @Input() set appUnless(condition: boolean) {
    if (!condition) this.viewContainer.createEmbeddedView(this.templateRef);
    else this.viewContainer.clear();
  }
}
Real-world example
A team builds a custom appUnless structural directive that shows content only when a condition is false, the exact opposite of ngIf, giving them a cleaner way to express certain conditions in their templates.
Likely follow-ups
  • How does the built in at if control flow syntax compare in performance to a custom structural directive like this?
  • What exactly does createEmbeddedView do behind the scenes?
Related topics