首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在QueryList中访问ElementRef

在QueryList中访问ElementRef
EN

Stack Overflow用户
提问于 2021-10-26 02:05:32
回答 1查看 66关注 0票数 0

我在访问Angular中的ElementRefs列表中的元素时遇到问题。我想遍历它们的整个列表,并相应地更新它们的CSS属性。

代码语言:javascript
复制
@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";
      }
  }

}

然而,我遇到了这个错误:

代码语言:javascript
复制
Element implicitly has an 'any' type because type 'QueryList<ElementRef<any>>' has no index signature. Did you mean to call 'get'?

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-26 13:33:37

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

代码语言:javascript
复制
@ViewChildren('div',  {read: ElementRef}) my_divs:QueryList<ElementRef>;

然后,我可以将for循环更改为forEach

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69716670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档