如何动态添加指令?

How to dynamically add a directive?

如何动态添加(注入)指令到主机?

我有一个 myTooltip 指令,我想将 mdTooltip 指令添加到它的宿主。我试过 setAttribute()ElementRef.nativeElement,但它没有创建 mdTooltip 指令。

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) */
  }
}

主机是指具有 myTooltip 指令的元素:

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

结果 不会在 html 以上改变,但在 mouseenter 上它会在 span 中有 md-tooltip 指令。

顺便说一句,我使用包装器而不是直接使用 md-tooltip 的原因是我想稍后修改显示延迟、隐藏延迟并以其他方式自定义 material 工具提示的行为。

编辑显然目前不支持动态添加指令:(我认为这个问题应该仍然存在,以防material团队更新

这是我们在 angular 中要求的功能...请阅读:https://github.com/angular/angular/issues/8785

一种快速而肮脏的方法是使用:

我有一个名为 myHilite 的指令(用于突出显示文本),我还有一个名为 MainComponent.ts 的组件。在 MainComponent.ts 我添加了这行代码...

export class MainComponent {
    @HostBinding('attr.myHilite') myHiliteDirective = new myHilite();
} 

如果您的指令需要参数...

export class MainComponent {
    @HostBinding('attr.myHilite') myHiliteDirective = new myHilite(this.elementRef);
}

你的指令可能需要在它的一个生命周期钩子中执行代码,像这样在父组件的生命周期钩子方法中手动调用指令的生命周期钩子方法...

export class MainComponent {
    //...code...

    ngOnInit(){
        this.myHiliteDirective.ngOnInit();
    }
}