首页 文章

如何在添加css类之后获取offsetWidth和offsetHeight值以更改它们

提问于
浏览
0

我有一个更新css类的Component

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

如何获取应用css后更改的新值?

1 回答

  • 0

    我用一个工作示例做了一个plnkr,你可以在这里找到它:plnkr,但结果似乎是预期的:

    679
    0
    
    210
    20
    

    所以在我看来它似乎正在工作......

    虽然我很确定在您的情况下没有运行更改检测,但您应该尝试手动调用它 .

    将其添加到构造函数中

    private changeDetectorRef: ChangeDetectorRef
    

    所以你的构造函数看起来像这样

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

    并调用这样的变化检测:

    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
    }
    

    现在你在控制台中看到的值应该没问题 .

相关问题