zZe*_*epo 8 javascript angular2viewencapsulation angular angular9
我试图通过添加实例 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 = ngHost.substr(ngHost.lastIndexOf('-') + 1)
}
Run Code Online (Sandbox Code Playgroud)
但我对这个解决方案并不完全满意,我正在寻找直接访问 id 的方法。
有谁知道如何访问这个?
Angular 9 中的唯一 ID 可以表示为:
_nghost - par - 2
| | |
static APP_ID componentDef.id
Run Code Online (Sandbox Code Playgroud)
为了访问,componentDef.id
您可以执行以下操作:
export class SomeComponent implements OnInit {
unique = this.constructor['?cmp'].id;
Run Code Online (Sandbox Code Playgroud)
?cmp
私有变量NG_COMP_DEF在哪里