【问题标题】:Angular Elements: Get a reference to host web component elementAngular Elements:获取对宿主 Web 组件元素的引用
【发布时间】:2022-12-09 16:05:24
【问题描述】:

使用 Angular Elements 时,我们通常会像这样将应用程序构建为 Web 组件:

export class AppModule implements DoBootstrap {

    ngDoBootstrap(appRef: ApplicationRef): void {
        customElements.define('foo', createCustomElement(AppComponent, {injector: appRef.injector}));
    }
}

综上所述,当在主机应用程序中插入主机标签时,相关的 DOM 片段如下所示:

...
<foo>
    #shadow-root
        (AppComponent's contents)

有没有办法将对托管 Web 组件的 &lt;foo&gt; 元素的引用(如 ElementRef)注入到 AppComponent 的构造函数中?

【问题讨论】:

  • ??这不是this.getRootNode().host 做的吗?? (当他们称 2.0 为升级)

标签: angular web-component angular-elements


【解决方案1】:

事实证明,注入到构造函数中的 ElementRef 恰好指向该元素(&lt;foo&gt; 标记),它是 Shadow DOM 的父元素:


constructor(private readonly el: ElementRef) {
    // el.nativeElement is <foo>
}

【讨论】:

    猜你喜欢
    • 2016-10-19
    • 2014-10-09
    • 2018-08-03
    • 2016-03-20
    • 2015-12-27
    • 2018-05-01
    • 2016-06-14
    • 2020-02-28
    • 1970-01-01
    相关资源
    最近更新 更多