Angular中如何在HTML模板内获取当前元素自身的id
Angular 元素内获取自身id的实现方案
Angular 模板表达式中的 this 默认指向组件类实例,而非当前渲染的DOM元素,因此直接写 {{this.id}} 只能读取组件中定义的id属性,无法获取DOM元素自身的id值。
针对你描述的「大量结构相似、排布无规律无法用ngFor生成、需要减少id硬编码重复」的场景,可使用以下方案:
方案1:同名模板引用变量(零额外逻辑,成本最低)
Angular 模板中,未绑定指令的模板引用变量会自动指向当前挂载的DOM元素,且同层级同名模板变量不会冲突——每个变量的作用域仅覆盖自身元素及其内部子节点,解析时会优先取最近的挂载元素。
你不需要为每个元素定义不同的变量名,只需要在需要引用自身id的元素上统一加一个固定的模板变量(比如#tile),内部直接读取变量的id属性即可:
<!-- 所有需要引用id的元素统一加#tile即可,不需要区分变量名 --> <mat-grid-tile #tile id="id1" colspan="4" rowspan="8" [ngClass]="{'selected': data[tile.id].select===true,'disabled':data[tile.id].open===0}" style="background: darkviolet;" class="hour"> <span>{{data[tile.id].name}}</span> <small>{{data[tile.id].time}}</small> </mat-grid-tile> <mat-grid-tile class="empty" colspan="4" rowspan="4"></mat-grid-tile> <mat-grid-tile #tile id="id2" colspan="2" rowspan="4" [ngClass]="{'selected': data[tile.id].select===true,'disabled':data[tile.id].open===0}" style="background: deeppink;" class="hour"> <span>{{data[tile.id].name}}</span> <small>{{data[tile.id].time}}</small> </mat-grid-tile> <mat-grid-tile #tile id="id3" colspan="2" rowspan="4" [ngClass]="{'selected': data[tile.id].select===true,'disabled':data[tile.id].open===0}" style="background: violet;" class="hour"> <span>{{data[tile.id].name}}</span> <small>{{data[tile.id].time}}</small> </mat-grid-tile>
这个方案下,你只需要维护元素上的id属性值,内部所有引用位置不需要再硬编码id字符串,修改id时仅需改一处即可。
方案2:自定义上下文指令(适合高复用场景)
如果不想在每个元素上加模板变量,可以封装一个极简的结构指令,自动将当前元素id注入模板上下文,使用时直接读取上下文变量即可:
- 定义指令:
import { Directive, Input, TemplateRef, ViewContainerRef, ElementRef, AfterViewInit } from '@angular/core'; @Directive({ selector: '[selfIdCtx]' }) export class SelfIdCtxDirective implements AfterViewInit { private templateRef!: TemplateRef<{ $implicit: string }>; constructor( private el: ElementRef<HTMLElement>, private vcRef: ViewContainerRef ) {} @Input() set selfIdCtx(tpl: TemplateRef<{ $implicit: string }>) { this.templateRef = tpl; } ngAfterViewInit() { this.vcRef.createEmbeddedView(this.templateRef, { $implicit: this.el.nativeElement.id }); } }
- 模板中使用:
<ng-container *selfIdCtx="let id"> <mat-grid-tile [id]="id" colspan="4" rowspan="8" [ngClass]="{'selected': data[id].select===true,'disabled':data[id].open===0}" style="background: darkviolet;" class="hour"> <span>{{data[id].name}}</span> <small>{{data[id].time}}</small> </mat-grid-tile> </ng-container>
这个方案需要额外在外层加ng-container包裹,适合后续需要统一扩展元素逻辑的场景。
避坑说明
不要在模板中通过$event、原生DOM API(如document.getElementById)获取元素id,这类写法会导致变更检测不可控,可维护性极差。
内容的提问来源于stack exchange,提问作者Sergio
相关产品推荐
相关产品推荐

