Angular CSS样式改变行项的宽度

问题描述 投票:0回答:1

我正在构思一个包含项目的水平条,它们必须是相同的宽度,它们之间有相同的间距,它们可以在垂直方向上任意展开(

这里是堆栈闪电战

nicely spaced

问题:如何自动设置行元素的宽度?如何自动设置行元素的宽度?这里我只是简单的放了一个好看的值。width:200px.

我希望它们的宽度取决于每行元素的数量。

我尝试了什么?用Horizontile中的elementRef(组件中的单个瓷砖,用*ngFor显示)来获取这个元素的宽度。

currentWidth:number;
constructor(private el:ElementRef) {}

  ngAfterViewInit(): void {
    this.currentWidth=this.el.nativeElement.offsetWidth;}

它返回5. (??)使用.width什么都不返回。另外,这也不推荐,我希望有另一种解决方案,减少耦合。

我注意到我可以使用 width:inherit; 的css中,这样我就可以从水平列表组件中设置样式。

<app-tile [style.width.px]="0.9*currentWidth/nDisplayedTiles" [tile]="item"></app-tile>

作为 currentWidth 值为零,当然不行。

我试着用%来设置,但是 inherits css标签保留了%,这并不是预期的效果,为什么app-tile的样式不受关注,如果 inherits 我试过使用ViewEncapsulation,但也没有效果。

但这看起来是个小问题:我是不是漏掉了什么?

css angular typescript
1个回答
1
投票

你可以使用 offsetParent (联系)的宽度,并创建一个方法来返回每个单元格的值,并在你的 [style.width.px],类似下面的东西就可以了。

HTMLElement.offsetParent 只读属性返回对最接近(在包含层次结构中最接近)定位的祖先元素的引用。

堆栈突击

ngAfterViewInit(): void {
    //added this as the compiler was throwing ExpressionChangedAfterItHasBeenCheckedError
    setTimeout(() => { 
      this.currentWidth=this.el.nativeElement.offsetParent.clientWidth;
    });
  }

  getWidth(): number{
     let width:number = 0;

     //you may need to change this value to better display the cells
     let multiplier = 0.7;

      width = (this.currentWidth * multiplier) / this.ndisplayTiles;

      width = Math.round(width);

      return width;
  }

<app-tile [class]="'layout-tile'" [tile]="item"  [style.width.px]="getWidth()">
</app-tile>
© www.soinside.com 2019 - 2024. All rights reserved.