4
votes

I have a Component which update css class

.slider-horizontal {
  width: 210px;
  height: 20px;
}
    import {Component, OnInit, Input, ViewChild, ElementRef, Renderer} from '@angular/core';
    export class SliderComponent implements OnInit {
      @ViewChild('picker') picker: ElementRef;

      constructor(private renderer: Renderer, private el: ElementRef) {

      }

      ngAfterViewInit() {
        this.renderer.setElementClass(this.picker.nativeElement, 'slider-horizontal', true);

        console.log(this.picker.nativeElement.offsetWidth);//old value 
        console.log(this.picker.nativeElement.offsetHeight);//old value
      }
    }

How do I get the new values which are changed after apply css?

1
Please provide a plunker demonstrating your problem.micronyks

1 Answers

1
votes

I made a plnkr with a working example you can find it here: plnkr, however the results seem to be as expected:

679
0

210
20

So in my plunk it appears to be working...

Although I'm pretty sure the change detection is not running in your case you should try to invoke it manually.

Add this to your constructor

private changeDetectorRef: ChangeDetectorRef

So your constructor would look like this

constructor(private renderer: Renderer,
            private el: ElementRef,
            private changeDetectorRef: ChangeDetectorRef) {

}

And call the change detection like this:

ngAfterViewInit() {
  this.renderer.setElementClass(this.picker.nativeElement, 'slider-horizontal', true);

  this.changeDetectorRef.detectChanges();

  console.log(this.picker.nativeElement.offsetWidth);//old value 
  console.log(this.picker.nativeElement.offsetHeight);//old value
}

Now the values you'll see in the console should be fine.