2

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Since I couldn't find any workaround, I accept this as the correct answer. Thanks.
0

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

1 Comment

Thanks for your answer. But the directive belongs to ngx-bootstrap dropdown module. So, I am not able to play with the internal structure.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.