// 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>