【问题标题】:How to access components unique encapsulation ID in Angular 9如何在 Angular 9 中访问组件的唯一封装 ID
【发布时间】:2020-05-23 15:54:46
【问题描述】:

我试图通过像这样添加实例 id 来封装我的元素 id:

<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。

类似这样的:

@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。

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 的直接访问。

有人知道如何访问吗?

【问题讨论】:

    标签: javascript angular angular9 angular2viewencapsulation


    【解决方案1】:

    Angular 9 中的唯一 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

    【讨论】:

    • 既然这是私有的,我们不应该避免使用它吗……否则它应该是一些公共 API 的一部分,对吧?
    • 这仅适用于组件的单个实例。基本上,它是组件 ID,而不是组件实例 ID,因此在呈现多个相同类型的组件时它不会是唯一的。
    猜你喜欢
    • 2020-07-10
    • 2020-05-30
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 2018-07-26
    • 2011-03-16
    相关资源
    最近更新 更多