我在访问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