Unsafe member access .setAttribute on an `any` value. eslint(@typescript-eslint/no-unsafe-member-access)

huangapple go评论116阅读模式
英文:

Unsafe member access .setAttribute on an `any` value. eslint(@typescript-eslint/no-unsafe-member-access)

问题

  1. 下面的代码中抛出了一个错误,但代码仍然按预期工作。

import { ..., ElementRef } from '@angular/core';

constructor(
...,
private elementRef: ElementRef
) { }

ngOnInit(): void {
const keyword: string = 'xyz';
this.elementRef.nativeElement.setAttribute('key', keyword); // gives error
}

  1. 错误 -
  2. > *在 'any' 值上的不安全成员访问 .setAttribute eslint([@typescript-eslint/no-unsafe-member-access](https://typescript-eslint.io/rules/no-unsafe-member-access/))*
  3. 怎么修复?
  4. 我尝试将 'keyword' 设置为字符串,但不起作用。
  5. `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.

  1. import { ..., ElementRef } from '@angular/core';
  2. constructor(
  3. ...,
  4. private elementRef: ElementRef
  5. ) { }
  6. ngOnInit(): void {
  7. const keyword: string = 'xyz';
  8. this.elementRef.nativeElement.setAttribute('key', keyword); // gives error
  9. }

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

  1. 解决方案 -
  2. const element: HTMLElement = this.elementRef.nativeElement as HTMLElement;
  3. element.setAttribute('key', keyword);
英文:

Solution -

  1. const element: HTMLElement = this.elementRef.nativeElement as HTMLElement;
  2. element.setAttribute('key', keyword);

huangapple
  • 本文由 发表于 2023年2月18日 18:51:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492815.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定