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

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

问题描述

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

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上会在span中包含md-tooltip指令.

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中使用的功能...请阅读以下内容:

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天全站免登陆