Angular - Possible to apply a directive conditionally?

Viewed 63

I need to create two different ul depending on type. If I have the type of first, then I want to apply the directive *dropdownMenu. Otherwise, there will be no directive for dropdown.

Is it possible to apply the directive conditionally so that there will be no duplicated code ?

    <ng-container *ngIf="type === 'first'">
      <ul *dropdownMenu item-directive [firstLevelItems]="items1" [secondLevelItems]="items2" [type]="type">
      </ul>
    </ng-container>

    <ng-container *ngIf="type !== 'first'">
      <ul item-directive [firstLevelItems]="items1" [secondLevelItems]="items2" [type]="type">
      </ul>
    </ng-container>
2 Answers

After Angular 2+, there is no way to apply directive based on conditionally. So need to duplicate code as you mentioned.

Simply pass argument to your directive (assuming that its your one). Something like.

<ul *dropdownMenu="type"></ul>

@Directive({ selector: '[dropdownMenu]' })
export class DropdownMenuDirective implements OnInit {
    private _type: string;
    
    constructor(
        private templateRef: TemplateRef<any>,
        private viewContainer: ViewContainerRef
    ) {}

    @Input()
    set dropdownMenu(type: string) {
        this._type = type
    }

    ngOnInit() {
        if (this._type === 'first') {
            this.viewContainer.clear() // to clear the view
        } else {
            this.viewContainer.createEmbeddedView(this.templateRef); // to create it
        }
    }
}
Related