4

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
  • 1
    Please provide a plunker demonstrating your problem.
    – micronyks
    Commented Jan 17, 2017 at 4:36

1 Answer 1

1

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.

3
  • I think the detectChanges is reduntant here. Would be great if @loi mai provide a real example
    – yurzui
    Commented Jan 17, 2017 at 5:30
  • @yurzui i remember having issues with this before and manually invoking the change detection solved it (RC builds though) but indeed a code example would be really useful Commented Jan 17, 2017 at 5:47
  • Thank you for your plnkr. That is exactly how my code look like. But I use angular-cli. Sometimes it í working correctly, but sometimes it is not. Also its width follows dynamically to web browsers window width when I do debug, I mean I changed the size of browser window while debugging. I add this.changeDetectorRef.detectChanges(); but no different.
    – loi mai
    Commented Jan 18, 2017 at 8:39

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.