简体   繁体   中英

Access ElementRef in QueryList

I'm having trouble accessing an element in a list of ElementRefs in Angular. I want to loop through the entire list of them and update their CSS properties accordingly.


@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";
      }
  }

}

However I'm running into this error:

Element implicitly has an 'any' type because type 'QueryList<ElementRef<any>>' has no index signature. Did you mean to call 'get'?

But when I change the indexing to a get I get possibly undefined...

I did change the decorator to ViewChildren but also added this:

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

Then I was able to change the for loop to a forEach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM