【问题标题】:Access ElementRef in QueryList在 QueryList 中访问 ElementRef
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 2021-07-22
    • 1970-01-01
    • 2019-09-08
    • 2019-03-24
    • 2019-02-22
    • 2023-03-05
    相关资源
    最近更新 更多