在angular 7中使用getElementById在DOM元素上应用指令 [英] Apply a directive on a DOM element using getElementById in angular 7

查看:99
本文介绍了在angular 7中使用getElementById在DOM元素上应用指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些由第三方生成的HTML(plotly),我很乐意在它创建的DOM元素之一上应用我们已经拥有的指令.

I have some HTML generated by a third party (plotly), and I would love to apply a directive that we already have on one of the DOM elements it creates.

该指令在单击时打开colorPicker并将颜色设置为字符串.

The directive opens a colorPicker on click and sets colors to strings.

我可以使用 querySelector getElementById 到达元素,但是如何将其转换/包装为有角度的元素可以向其中添加指令?

I can reach the element with querySelector, or getElementById, but how can I transform / wrap it into angular can add a directive to?

我尝试过:

 const el = document.getElementById('myEl');
 const comp = new ElementRef(el)

或:

const comp = this.renderer.selectRootElement(el)

但是 comp 并没有提供帮助

推荐答案

如果生成此HTML,我建议为此库添加一个包装器组件.在内部,可以有一个DIV来包装要放置生成的HTML的位置,然后在该包装上添加指令.

If this HTML is generated, I suggest to add a wrapper component for this library. Inside, you can have a DIV wrapping the place where you would put your generated HTML and on that wrapper you can add your directive.

类似的东西:

@Component({
    selector: 'lib-wrapper',
    template: '<div myDirective><div #placeholder></div></div>',
})
export class LibWrapperComponent {
    @ViewChild('placeholder')
    placeholder: ElementRef<HTMLElement>;

    ngAfterViewInit() {
        myLibrary.doStuffOnElement(this.placeholder.nativeElement);
    }
}

编辑:如果您的指令完成了您所需的全部操作,但问题是您需要绑定到该元素的元素嵌套得很深,则可以使用选择器将输入添加到您的指令中:

If your directive does all that you need but your problem is that the element you need to bind it to is nested deep, you can add input to your directive with a selector:

@Directive({
  selector: 'clickListener',
})
export class ClickListener {
  @Input()
  clickListenerSelector = '';

  constructor(
    @Inject(ElementRef) private readonly elementRef: ElementRef<HTMLElement>,
  ) {}

  @HostListener('click', ['$event.target'])
  onClick(target: HTMLElement) {
    if (this.host.contains(target) {
       // Do your logic here
    }
  }

  private get host(): HTMLElement {
    return !this.clickListenerSelector
      ? this.elementRef.nativeElement
      : (this.elementRef.nativeElement.querySelector(this.clickListenerSelector) || this.elementRef.nativeElement);
  }

}

这样,您可以将指令添加到wrapper元素并将选择器传递给它.如果您没有通过选择器,它将像现在一样工作,如果选择器没有找到任何东西,它也会使用其ElementRef元素,就像没有选择一样.

This way you can add your directive to the wrapper element and pass selector to it. In case you did not pass a selector it would work like it works now, if selector didn't find anything it would also use its ElementRef element, like it does not.

这篇关于在angular 7中使用getElementById在DOM元素上应用指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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