简体   繁体   English

如何获取Angular中的组件唯一封装ID 9

[英]How to access components unique encapsulation ID in Angular 9

I'm trying to encapsulate my element ids by adding the instance id like this:我试图通过添加实例 ID 来封装我的元素 ID,如下所示:

<label for="id-{{ unique }}-name"></label>
<input id="id-{{ unique }}-name" type="text" formControlName="name">

I previously worked with this: https://stackoverflow.com/a/40140762/12858538 .我以前使用过这个: https://stackoverflow.com/a/40140762/12858538 But after upgrading Angular from 7 to 9 this seems deprecated.但是在将 Angular 从 7 升级到 9 之后,这似乎已被弃用。 I was thinking about a simple helper service, which would generate unique ids for my app.我在考虑一个简单的帮助服务,它会为我的应用程序生成唯一的 ID。

Something like this:像这样:

@Injectable()
export class UniqueIdService {
  private counter = 0

  constructor() {}

  public getUniqueId (prefix: string) {
    const id = ++this.counter
    return prefix + id
  }
}

inspired by lodash uniqueid灵感来自 lodash uniqueid

But I did rather use angulars build in ids.但我宁愿使用 angulars 构建在 ids 中。 So my currently solution is to extract the id from the components _nghost attribute.所以我目前的解决方案是从 components _nghost属性中提取 id。

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

But I'm not perfectly happy with this solution and I'm looking for a direct access to the id.但我对这个解决方案不是很满意,我正在寻找直接访问 id 的方法。

Does anyone know how to access this?有谁知道如何访问这个?

The unique ID in Angular 9 can be represented as: Angular 9 中的唯一 ID 可以表示为:

_nghost   -   par    -     2
   |           |           |
 static      APP_ID   componentDef.id

In order to access componentDef.id you can do the following:为了访问componentDef.id您可以执行以下操作:

export class SomeComponent implements OnInit {
  unique = this.constructor['ɵcmp'].id;

where ɵcmp is a private variable NG_COMP_DEF其中ɵcmp是一个私有变量NG_COMP_DEF

Ng-run Example 吴运行示例

Neither _nghost nor ɵcmp are unique across component instances. _nghostɵcmp在组件实例中都不是唯一的。 They should not be used for that purpose.它们不应该用于该目的。

Your UniqueIdService is the easiest and the safest solution.您的UniqueIdService是最简单和最安全的解决方案。 (The counter property could be static to be sure that every instance of the service returns unique ID). counter属性可以是 static 以确保服务的每个实例都返回唯一 ID)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM