使用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
相关产品推荐
相关产品推荐

