【发布时间】:2021-12-11 10:43:45
【问题描述】:
我在访问 Angular 中的 ElementRefs 列表中的元素时遇到问题。我想遍历它们的整个列表并相应地更新它们的 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,而不是ViewChild
-
我确实将其更改为 ViewChildren,但这仍然不能让我正确索引它
标签: javascript html angular dom web-frontend