You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取mat-radio-button绑定的data-attribute属性值

问题场景

在*ngFor循环中渲染Angular Material的mat-radio-button组件时,需要读取组件上绑定的data-*自定义属性,两种自行尝试的方案均未达到预期:

  • 方案1:在change事件回调中从事件对象读取目标属性,返回结果为undefined
  • 方案2:通过模板引用变量#radioEle获取ElementRef实例,编程访问时无法定位到对应的data-attribute属性
  • 现象确认:控制台查看组件嵌套的原生DOM元素时,绑定的data-attribute属性是正常渲染存在的
问题相关代码

模板代码

<mat-radio-group [formControlName]="resp.questionPartId">
  <ng-container *ngFor="let option of question.questionParts[i].questionChoices; let optIndex = index">
    <mat-radio-button 
      [value]="option.value"
      [attr.data-skip]="option.skipId"   
      #radioEle 
      (change)="skipQuestion($event, messageEl)">
      {{option.name}}
    </mat-radio-button>
  </ng-container>
</mat-radio-group>

TS逻辑代码

skipQuestion(event: any, el: any): void {
  console.log('skip question function : ', event);
  console.log('skip question function : ', event, el.source._elementRef.nativeElement.attributes);
}
问题原因
  1. 模板引用变量直接写在Angular组件标签上时,默认获取的是组件类实例,不是原生DOM元素,所以直接拿radioEle读属性会找不到
  2. mat-radio-button的change事件抛出的是MatRadioChange类型的自定义事件对象,不是原生DOM change事件,事件对象上的target不指向绑定data-skip的内部原生节点,直接读属性自然返回undefined
可行解决方案

方案1:直接把需要的参数传进回调(最推荐,无DOM操作、稳定性最高)

不需要绕路读DOM属性,直接在模板触发事件时把循环项里的option.skipId作为参数传入即可:

模板修改

<mat-radio-button 
  [value]="option.value"
  (change)="skipQuestion($event, messageEl, option.skipId)">
  {{option.name}}
</mat-radio-button>

TS接收参数

// 记得从@angular/material/radio引入MatRadioChange类型
skipQuestion(event: MatRadioChange, el: ElementRef, skipId: string | number): void {
  console.log('当前选项绑定的skipId为:', skipId);
  // 后续业务逻辑直接使用skipId即可
}

方案2:通过组件实例读取原生元素的data属性

如果一定要读DOM上的data-*属性,需要先拿到mat-radio-button的组件实例,再从实例持有的原生元素引用上读取:

模板修改

<mat-radio-button 
  [value]="option.value"
  [attr.data-skip]="option.skipId"   
  #radioEle="matRadioButton" 
  (change)="skipQuestion(radioEle, messageEl)">
  {{option.name}}
</mat-radio-button>

TS读取属性

// 记得从@angular/material/radio引入MatRadioButton类型
skipQuestion(radioInstance: MatRadioButton, el: ElementRef): void {
  // 从组件实例关联的原生元素上通过dataset API读取data属性
  const skipId = radioInstance._elementRef.nativeElement.dataset.skip;
  console.log('读取到的skipId为:', skipId);
}

注意:_elementRef是组件内部私有属性,框架大版本升级时存在改名风险,优先使用方案1传参的方式更稳妥。

内容的提问来源于stack exchange,提问作者Tej

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 13:19:06