Skip to content

Instantly share code, notes, and snippets.

@WodenWang820118
Last active January 28, 2023 08:29
Show Gist options
  • Save WodenWang820118/cdd34d2d3c115ea46c02b71c82d9e55a to your computer and use it in GitHub Desktop.
Save WodenWang820118/cdd34d2d3c115ea46c02b71c82d9e55a to your computer and use it in GitHub Desktop.
// custom directive used like *ngIf
// the "*" instantiates an ng-template and inject it to DOM
// possible use case could be showing and hiding content depending on user roles
// ngx, the x is a convention explicitly saying the directive is the custom one
// [ngx-unless]

import { Directive, Input, TemplateRef, ViewContainerRef } from "@angular/core";

@Directive({
  selector: "[ngxUnless]",
})
export class NgxUnlessDirective {
  visible = false;
  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef
  ) {}

  @Input()
  set ngxUnless(condition: boolean) {
    if (!condition && !this.visible) {
      this.viewContainer.createEmbeddedView(this.templateRef);
      this.visible = true;
    } else if (condition && this.visible) {
      this.viewContainer.clear();
      this.visible = false;
    }
  }
}
// [app.component.html]
// meant to make the condition opposite to demonstrate structral directive
<!-- the "*" creates a ng-template and instantiates it -->
    <course-image
      [src]="course.iconUrl"
      *ngxUnless="!course.iconUrl"
    ></course-image>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment