小编zZe*_*epo的帖子

如何在 Angular 9 中访问组件唯一的封装 ID

我试图通过添加实例 id 来封装我的元素 id,如下所示:

<label for="id-{{ unique }}-name"></label>
<input id="id-{{ unique }}-name" type="text" formControlName="name">
Run Code Online (Sandbox Code Playgroud)

我以前使用过这个: 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
  }
}
Run Code Online (Sandbox Code Playgroud)

灵感来自 lodash uniqueid

但我宁愿使用 ids 中构建的角度。所以我目前的解决方案是从组件属性中提取 id _nghost

constructor ( private element: ElementRef, ) {
   const ngHost = 
     Object.values(this.element.nativeElement.attributes as NamedNodeMap)
     .find(attr => attr.name.startsWith('_nghost'))
     .name
   this.unique = …
Run Code Online (Sandbox Code Playgroud)

javascript angular2viewencapsulation angular angular9

8
推荐指数
1
解决办法
3077
查看次数