在组件中更新绑定变量时,Angular 6 style.property 或 ngStyle 不更新

rth*_*s62 2 javascript ng-style angular

我正在尝试创建一个简单的轮播,然后单击我正在尝试更新元素上的 style.transform 以更新 translate3d,以便它会移动。组件中绑定的变量会更新,但 dom 上不会更新。

滑动函数触发了translate3d中的变化,它正在更新组件内部的变量。它只是没有在 dom 上更新。

当我动态更改 style.width.px 时它会起作用。

这是我的组件。

export class RecentNewsSliderComponent implements OnInit, AfterViewInit {    

  @ViewChild('recentNewsSlider') recentNewsSlider;
  @Input() articles;

  newsContainerWidth: number;
  carousel: any = {};

  constructor() { }

  ngOnInit() {
    this.setUpCarousel();
  }

  ngAfterViewInit() {
    setTimeout(() => this.newsContainerWidth = this.getNewsContWidth(), 500);
  }

  setUpCarousel() {
    this.carousel.articlesLength = this.articles.length;
    this.carousel.controls = [];
    this.carousel.transform3d = 'translate3d(0, 0, 0)';
    let controlsNum = Math.ceil(this.articles.length / 3);

    for(let i = 0; i < controlsNum; i++) {
      this.carousel.controls.push({ i: i, active: i === 0 ? true : false });
    }
  }


  getNewsContWidth() {
    let totalWidth = 0;
    let children = Array.from(this.recentNewsSlider.nativeElement.children);    

    children.forEach((x: any) => {      
      totalWidth += x.offsetWidth;
    });

    this.carousel.containerWidth = totalWidth + (children.length * 20);

    return totalWidth + (children.length * 20);
  }

  slide(control) {
    let scrollTo = this.carousel.containerWidth /     this.carousel.controls.length;

    if(control.i === 0) {
      this.carousel.transform3d = 'translate3d(0, 0, 0)';
    } else {
      this.carousel.transform3d = `translate3d(${scrollTo}, 0, 0)`
    }    
  }

}
Run Code Online (Sandbox Code Playgroud)

这是我的 HTML。

<div class="news-wrapper container">
    <div #recentNewsSlider class="news-container" [style.width.px]="newsContainerWidth" [style.transform]="carousel.transform3d">
        <div *ngFor="let article of articles">
          <div class="news-article">
            <img src="{{ article.image }}">
            <div class="rollover">
              <h4>{{ article.title }}</h4>
              <button class="small">Read</button>
            </div>
          </div>
        </div>
    </div>
    <div class="row">
      <div class="col-md-12">
        <div class="news-control">
          <div class="dot" *ngFor="let control of carousel.controls" [ngClass]="{ 'active' : control.active }" (click)="slide(control)"></div>
        </div>
      </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

rth*_*s62 5

我没有在数字后面包含 px。