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

使用Angular Renderer2添加类时触发Cannot read properties of undefined错误

问题分析与解决方案:Angular Dropdown指令中Cannot read properties of undefined (reading 'add')错误

错误原因

调用Renderer2.addClass()和removeClass()时,传入的第一个参数是ElementRef实例,但该方法要求第一个参数必须是真实的DOM元素对象。ElementRef是Angular封装的引用容器,需通过它的nativeElement属性才能获取对应的DOM节点。

修正后的代码

@Directive({
  selector: '[appDropdown]',
})

export class DropdownDirective {
  isClassApplied: boolean;
  @Input('appDropdown') className: string;

  constructor(private renderer: Renderer2, private elRef: ElementRef) {
    this.isClassApplied = false;
  }

    @HostListener('click') onClickAddClass() {
        if (!this.isClassApplied) {
            this.isClassApplied = true;
            // 改为访问nativeElement属性获取真实DOM节点
            this.renderer.addClass(this.elRef.nativeElement, this.className);
        } else {
            this.isClassApplied = false;
            // 改为访问nativeElement属性获取真实DOM节点
            this.renderer.removeClass(this.elRef.nativeElement, this.className);
        }
    }
}

简化优化(可选)

可以通过状态取反简化逻辑:

@HostListener('click') onClickAddClass() {
  this.isClassApplied = !this.isClassApplied;
  const action = this.isClassApplied ? 'addClass' : 'removeClass';
  this.renderer[action](this.elRef.nativeElement, this.className);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:33:01