如何在Angular 9中访问组件的唯一封装ID [英] How to access components unique encapsulation ID in Angular 9
问题描述
我试图通过添加实例ID来封装我的元素ID:
I'm trying to encapsulate my element ids by adding the instance id like this:
<label for="id-{{ unique }}-name"></label>
<input id="id-{{ unique }}-name" type="text" formControlName="name">
我以前曾使用过此软件: https://stackoverflow.com/a/40140762/12858538 . 但是在将Angular从7升级到9之后,这似乎已被弃用.我当时在考虑一个简单的帮助程序服务,该服务会为我的应用程序生成唯一的ID.
I previously worked with this: https://stackoverflow.com/a/40140762/12858538. But after upgrading Angular from 7 to 9 this seems deprecated. I was thinking about a simple helper service, which would generate unique ids for my app.
类似这样的东西:
@Injectable()
export class UniqueIdService {
private counter = 0
constructor() {}
public getUniqueId (prefix: string) {
const id = ++this.counter
return prefix + id
}
}
灵感来自lodash uniqueid
但是我宁愿使用ids中的angulars内置.
因此,我目前的解决方案是从组件_nghost
属性中提取ID.
But I did rather use angulars build in ids.
So my currently solution is to extract the id from the components _nghost
attribute.
constructor ( private element: ElementRef, ) {
const ngHost =
Object.values(this.element.nativeElement.attributes as NamedNodeMap)
.find(attr => attr.name.startsWith('_nghost'))
.name
this.unique = ngHost.substr(ngHost.lastIndexOf('-') + 1)
}
但是我对这种解决方案并不完全满意,我正在寻找直接访问ID的方法.
But I'm not perfectly happy with this solution and I'm looking for a direct access to the id.
有人知道如何访问吗?
推荐答案
Angular 9中的唯一ID可以表示为:
The unique ID in Angular 9 can be represented as:
_nghost - par - 2
| | |
static APP_ID componentDef.id
要访问componentDef.id
,您可以执行以下操作:
In order to access componentDef.id
you can do the following:
export class SomeComponent implements OnInit {
unique = this.constructor['ɵcmp'].id;
Ng-run Example
这篇关于如何在Angular 9中访问组件的唯一封装ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!