将ng-content元素的宽度设置为通过的子元素的大小

时间:2018-07-05 09:38:31

标签: angular typescript

我有一个看起来像这样的视图:

<base-carousel>
  <div *ngFor="let item of items" carouselItem>
    <!-- content -->
  </div>
</base-carousel>

base-carousel的模板如下所示:

<div [style.width]="getTrackWidth()">
  <ng-content select="[carouselItem]"></ng-content>
</div>

base-carousel的类如下所示:

@ContentChildren(CarouselItem, {read: ElementRef}) items: ElementRef[];

getTrackWidth(): string {
  return this.items.reduce((accum, curr) =>
      accum + curr.nativeElement.clientWidth, 0) + 'px';
}

问题是,这引发了错误:ExpressionChangedAfterItHasBeenCheckedError

然后我尝试将[style.width]更改为指向一个简单变量,而我的班级看起来更像这样:

trackWidth = '100%';

ngAfterViewInit() {
  this.setTrackWidth();
  this.changeDetector.detectChanges();
}

setTrackWidth(): string {
  this.trackWidth = this.items.reduce((accum, curr) =>
      accum + curr.nativeElement.clientWidth, 0) + 'px';
}

这可以修复错误,但是现在宽度始终设置为零,并且不会占用子级渲染的大小。

1 个答案:

答案 0 :(得分:0)

我发现使用ngAfterContentInit是正确的生命周期挂钩,可以解决我的问题。

相关问题