Ric*_*ock 26 typescript angular2-directives angular
如何动态添加(注入)指令到主机?
我有一个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的原因是我想稍后修改显示延迟,隐藏延迟并以其他方式定制材料工具提示的行为.
编辑显然目前不支持动态添加指令:(我认为这个问题仍应存在,以防材料团队更新
bti*_*oco 25
这是我们要求角色的一个功能...阅读本文: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();
    }
}
| 归档时间: | 
 | 
| 查看次数: | 24354 次 | 
| 最近记录: |