MaxImpact
MaxImpact

Reputation: 5

Angular 2 using ngOnInit to apply style attribute

While the code below produces no errors when I inspect the elements, the styles are not applied to the elements with class="circle". Please don't refer me to ngStyle, I want to know why this isn't working.

export class PlayersComponent implements OnInit {
        items: any;

        ngOnInit() {

          this.items = document.querySelector('.circle');
          for(var i = 0; i < this.items.length; i++){
            if(i % 2 == 0) {
            this.items[i].style.color = '#0000FF';
            }
            else {
              this.items[i].style.color = '#FF0000';
            }
          }
        }
    }

Upvotes: 0

Views: 3164

Answers (2)

JayChase
JayChase

Reputation: 11525

The elements will not have been rendered yet in OnInit. You would need to use AfterViewInit and also querySelectAll to get all the elements.

    export class AppComponent implements AfterViewInit {
    items: any;

    ngAfterViewInit() {
      this.items = document.querySelectorAll('.circle');
      for (let i = 0; i < this.items.length; i++) {
        if (i % 2 === 0) {
          this.items[i].style.color = '#0000FF';
        }
        else {
          this.items[i].style.color = '#FF0000';
        }
      }
    }
  }

Accessing the DOM in this way is not a good idea in Angular 2 though. This article is a good guide to doing things the Angular way.

Upvotes: 2

chrispy
chrispy

Reputation: 3612

Like the others have said, manipulating the DOM like that in Angular 2 is not usually the preferred approach.

But, if you're looking to do this, you should probably call ngAfterViewInit (a lifecycle hook like ngOnInit) to ensure that the DOM elements are present before running your code.

Another problem could possibly be that you aren't manipulating the right DOM elements, but it's impossible to tell without more information.

Upvotes: 1

Related Questions