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

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

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);

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:

确定