Angular9中如何获取组件唯一封装ID

How to access components unique encapsulation ID in Angular 9

我正在尝试通过添加实例 ID 来封装我的元素 ID,如下所示:

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

我以前用过这个:。 但是在将 Angular 从 7 升级到 9 之后,这似乎已被弃用。我在考虑一个简单的帮助服务,它会为我的应用程序生成唯一的 ID。

像这样:

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

  constructor() {}

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

灵感来自 lodash uniqueid

但我宁愿使用 angulars 构建在 ids 中。 所以我目前的解决方案是从组件 _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)
}

但我对这个解决方案不是很满意,我正在寻找直接访问 id 的方法。

有人知道如何访问吗?

Angular9中的唯一ID可以表示为:

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

要访问 componentDef.id,您可以执行以下操作:

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

其中 ɵcmp 是私有变量 NG_COMP_DEF

Ng-run Example