访问 QueryList 中的 ElementRef

Access ElementRef in QueryList

我无法访问 Angular 中 ElementRef 列表中的元素。我想遍历它们的整个列表并相应地更新它们的 CSS 属性。


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  @ViewChild('div') my_divs:QueryList<ElementRef>;

  constructor() {
  }

  ngAfterViewInit() {
  }

  do_something() {
      for(var i=0; i<this.my_divs.length; i++){
        //THIS IS WRONG
        this.my_divs[i].nativeElement.style.background_color = "red";
      }
  }

}

但是我 运行 遇到了这个错误:

Element implicitly has an 'any' type because type 'QueryList<ElementRef<any>>' has no index signature. Did you mean to call 'get'?

但是当我将索引更改为 get 时,我可能未定义...

我确实将装饰器更改为 ViewChildren,但还添加了以下内容:

@ViewChildren('div',  {read: ElementRef}) my_divs:QueryList<ElementRef>;

然后我能够将 for 循环更改为 forEach