簡體   English   中英

在 QueryList 中訪問 ElementRef

[英]Access ElementRef in QueryList

我在 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 但也添加了以下內容:

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

然后我能夠將for循環更改for forEach

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM