您可以获得组件封装主机ID吗? [英] Can you get the component encapsulation host ID?
问题描述
有没有办法获取赋予组件的封装主机ID?
Is there a way to get the encapsulation host id that is given to a component?
如果您有使用ViewEncapsulation.Emulated
的组件,则 DOM 中的元素将具有类似_nghost-par-2.
的属性名称,即唯一ID 赋予组件以封装相关的样式.
If you have a component that is using ViewEncapsulation.Emulated
the element in the DOM will have an attribute name of something like _nghost-par-2.
Which, is a unique ID given to the component to encapsulate the associated styles.
如何获取该ID作为组件的构造函数的一部分?
How do you get that ID as part of the component's constructor?
以下方面的作用:
@Component({
hostId:string;
...
})
export class myComponent implements OnInit {
constructor(host:Host) {
this.hostId = host.id;
}
...
}
推荐答案
此ID由以下部分组成:
This ID consists of the following parts:
_nghost - par - 2
| | |
static APP_ID _nextCompTypeId
APP_ID 是来自@ angular/core的公正令牌
APP_ID is a just token from @angular/core
如果您需要避免将随机生成的值用作 应用程序ID,您可以通过DI提供程序提供自定义值 使用此令牌配置根注入器
If you need to avoid randomly generated value to be used as an application id, you can provide a custom value via a DI provider configuring the root Injector using this token
_nextCompTypeId 是在私有类ViewUtils
中的框架内部生成的.
_nextCompTypeId is generated inside framework within private class ViewUtils
.
似乎没有公共方法可以返回其值.因此,以下方法可能会起作用
Seems there is no a public method which can return it value. So probably the following will work
export class MyComponent {
id: string;
constructor(@Inject(APP_ID) appId: string, vcRef: ViewContainerRef) {
this.id = `${appId}-${vcRef.injector['_view'].viewUtils._nextCompTypeId - 1}`;
}
}
另一种方法是通过elementRef
If you're on Angular 9 then follow this answer How to access components unique encapsulation ID in Angular 9
这篇关于您可以获得组件封装主机ID吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!