How to dynamically add a directive?

Discussão em 'Angular' iniciado por RichieRock, Março 19, 2025.

  1. RichieRock

    RichieRock Guest

    How to dynamically add (inject) a directive into host?

    I have a myTooltip directive and I would like to add mdTooltip directive to it's host. I have tried setAttribute() of ElementRef.nativeElement, but it doesn't create the mdTooltip directive.

    mytooltip.directive.ts:

    @Directive({
    selector: '[my-tooltip]',
    host: {
    '(mouseenter)': 'show()',
    '(mouseleave)': 'hide()',
    }
    })
    export class myTooltip {
    @Input('my-tooltip') message;

    constructor() { }

    show() {
    /* TODO: How to add md-tooltip directive to elementref (host)? */
    }

    hide() {
    /* TODO: remove md-tooltip directive from elementref (host) */
    }
    }


    By host I mean the element that has myTooltip directive:

    <span my-tooltip="tooltip hint">Click here</span>


    The result wouldn't change above html but on mouseenter it would have md-tooltip directive in span.

    BTW, the reason I am using a wrapper and not directly md-tooltip is that I want to later modify the showing delay, hiding delay and customize material tooltip's behaviour in other means as well.

    Edit Apparently adding directives dynamically is not currently supported :( I think this question should still be here in case it material team updates that

    Continue reading...

Compartilhe esta Página