A custom structural directive in Angular is a directive that can be used to dynamically add, remove, or replace elements in the DOM. Structural directives are prefixed with an asterisk (*), such as ngIf and ngFor.
Let's create a UnlessDirectiive which is exactly the opposite of the NgIf directive. NgIf displays the template content when the condition is true. UnlessDirective displays the content when the condition is false.
import { Directive, Input } from '@angular/core';
@Directive({
selector: '[appUnless]'
})
export class HighlightDirective implements OnInit{
@Input() set appUnless(condition : boolean){
if(!condition){
this.viewContainer.createEmbeddedView(this.templateRef);
}
else{
this.viewContainer.clear();
}
}
constructor(private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef){}
}
// In HTML
<div *appUnless="condition">
//content
</div>