如何动态添加指令? [英] How to dynamically add a directive?

查看:19
本文介绍了如何动态添加指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将指令动态添加(inject)到主机中?

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

我有一个 myTooltip 指令,我想向它的主机添加 mdTooltip 指令.我已经尝试了 ElementRef.nativeElementsetAttribute(),但它没有创建 mdTooltip 指令.

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:

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 指令的元素:

By host I mean the element that has myTooltip directive:

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

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

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

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

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

推荐答案

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

That is a feature we are asking for in angular...read this: https://github.com/angular/angular/issues/8785

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

A quick and dirty way to do it is to use:

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

I have a directive named myHilite (to highlight text), I also have a component named MainComponent.ts. In MainComponent.ts I added this line of code...

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

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

If your directive requires parameters...

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

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

Your directive may need to execute code in one of its life cycle hooks, manually call the directive's lifecycle hook method in the parent component's lifecycle hook method like this...

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

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

这篇关于如何动态添加指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆