Home > Software design >  Access ElementRef in QueryList
Access ElementRef in QueryList

Time:10-30

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...

CodePudding user response:

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

  • Related