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

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

问题描述

我有一些由第三方(plotly)生成的 HTML,我很想在它创建的其中一个 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.

我可以使用 querySelectorgetElementById 访问该元素,但是如何转换/包装它以便添加指令?

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

我试过了:

 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);
  }

}

通过这种方式,您可以将指令添加到包装元素并将选择器传递给它.如果你没有传递选择器,它会像现在一样工作,如果选择器没有找到任何东西,它也会使用它的 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天全站免登陆