角度错误 - “赋值表达式的左侧可能不是可选属性 access.ts”?

Par*_*h M 11 runtime-error typescript angular

在我的 Angular 打字稿文件中,我有以下代码。我需要帮助来解决这个打字稿错误

ngAfterViewInit() {
 setTimeout(() => {
 this.tada = document.querySelectorAll('.highlighted').length;
document.querySelector<HTMLElement>('.highlighted')?.style.backgroundColor = 'pink';->>Error
        this.fckme();
      }, 50);
    }
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

The left-hand side of an assignment expression may not be an optional property access.ts(2779)

Run Code Online (Sandbox Code Playgroud)

我创建了自定义管道,如果我循环遍历文本并搜索单词,如果给定文本中存在单词,我会向其中添加突出显示的类,以便我可以用粉红色突出显示该单词

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'highlight'
})
export class HiPipe implements PipeTransform {

  transform(v1: string, v2: string): unknown {
   //some code
    for (const match of matches) {
      value = value.replaceAll(match, `<span class = "highlighted data-${match}">${match}</span>`);
    }
    return v1;
  }
}
Run Code Online (Sandbox Code Playgroud)

Job*_*lle 11

把里面的问号去掉就可以了

document.querySelector<HTMLElement>('.highlighted')?.style.backgroundColor = 'pink';
Run Code Online (Sandbox Code Playgroud)

对于错误。

它应该是

if(document.querySelector<HTMLElement>('.highlighted')){
    document.querySelector<HTMLElement>('.highlighted').style.backgroundColor = 'pink';
}
Run Code Online (Sandbox Code Playgroud)

因为那个 ?将 document.querySelector('.highlighted') 设为可选,在右侧我们为其赋值。

但它会将第一个具有“突出显示”类的项目设置为粉红色。因此,您需要循环遍历元素或为其添加粉红色类。并将该类项目的背景颜色设置为粉红色

尝试使用下面的代码来更改突出显示类的所有元素。

const elements = document.querySelectorAll('.highlighted');
    if(elements.length){
      elements.forEach((item:HTMLElement) => {
        item.style.backgroundColor = 'pink';
      })
    }
Run Code Online (Sandbox Code Playgroud)

检查这个https://stackblitz.com/edit/angular-services-example-ygmmaq?file=src/app/app.component.html

  • 从 `document.querySelector&lt;HTMLElement&gt;('.highlighted').style.backgroundColor = 'white'` 中删除 `?` 时,它表示 `Object 可能是 'null'.ts(2531) ` (3认同)

Ric*_*e50 0

未在文档对象上正确设置转换

ngAfterViewInit() {
setTimeout(() => {
//this.tada = document.querySelectorAll('.highlighted').length;
//you don't need this unless you are trying to apply the pink colour to all class with the selector above. returns an array of all elements with class highlighted
let highlight: Array<HTMLElement> = <HTMLElement>document.querySelectorAll('.highlighted');
//or let highlight:HTMLCollection[] = Array.from(document.getElementsByClassName('highlighted') as HTMLCollection<HTMLElement>)
highlight.forEach((el:HTMLElement) => {
 if(!el) return;
el.style.backgroundColor = 'pink';
});
,0}
}

Run Code Online (Sandbox Code Playgroud)

请参阅此链接以获取更多信息 Typescript 3.7@beta 可选链接运算符使用问题