英文:
Unsafe member access .setAttribute on an `any` value. eslint(@typescript-eslint/no-unsafe-member-access)
问题
下面的代码中抛出了一个错误,但代码仍然按预期工作。
import { ..., ElementRef } from '@angular/core';
constructor(
...,
private elementRef: ElementRef
) { }
ngOnInit(): void {
const keyword: string = 'xyz';
this.elementRef.nativeElement.setAttribute('key', keyword); // gives error
}
错误 -
> *在 'any' 值上的不安全成员访问 .setAttribute。 eslint([@typescript-eslint/no-unsafe-member-access](https://typescript-eslint.io/rules/no-unsafe-member-access/))*
怎么修复?
我尝试将 'keyword' 设置为字符串,但不起作用。
`this.elementRef.nativeElement.setAttribute('key', keyword as string);`
英文:
An error is being thrown from the below code, but the code is still working as expected.
import { ..., ElementRef } from '@angular/core';
constructor(
...,
private elementRef: ElementRef
) { }
ngOnInit(): void {
const keyword: string = 'xyz';
this.elementRef.nativeElement.setAttribute('key', keyword); // gives error
}
Error -
> Unsafe member access .setAttribute on an 'any' value. eslint(@typescript-eslint/no-unsafe-member-access)
Whats's the fix?
I was trying to set 'keyword as string', but not working.
this.elementRef.nativeElement.setAttribute('key', keyword as string);
答案1
得分: -1
解决方案 -
const element: HTMLElement = this.elementRef.nativeElement as HTMLElement;
element.setAttribute('key', keyword);
英文:
Solution -
const element: HTMLElement = this.elementRef.nativeElement as HTMLElement;
element.setAttribute('key', keyword);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论