【问题标题】:How to pass value from typescript code to css in Angular 6如何在Angular 6中将值从打字稿代码传递到css
【发布时间】:2021-03-14 08:01:09
【问题描述】:

我知道我必须使用ngClassngStyle,但我不知道如何传递该值。这是我的代码。

strip.component.ts

import { ... } from '@angular/core';

@Component({
    selector: 'app-strip',
    templateUrl: './strip.component.html'
})
export class StripComponent implements OnInit {
    ...
    @Input() widthValue: any; // getting this from parent component

    staticKpi:{...}=[][]
}

strip.component.html

<ng-container>
    <div *ngFor="let row of staticKpi">
        <div class="rows" *ngFor="let item of row">
            <div class="col-12">
                <h2>{{widthValue}}</h2> <!-- this is printing correct value-->
                ...
            </div>
        </div>
    </div>
</ng-container>

我必须在 scss 中动态决定 rows 类的宽度,如下所示:

strip.component.css

.rows {
    display: inline-block;
    width: calc(100%/widthValue); // <----- here
    text-align: left !important;
    background: red;
}

我本可以在 HTML 中使用col-{{widthValue}},但不,我被告知它必须来自 CSS 的 width 属性。 请帮我。我不确定如何在这里使用 ngClass。

【问题讨论】:

  • 使用ngStyle动态设置宽度。
  • 你可以在.html中使用:[style.width]="(100/widthValue)+'%'"[ngClass]="'col-'+widthValue"
  • @Eliseo,这不起作用。元素刚刚相互碰撞,就好像宽度为零一样。 :-(
  • 您可以使用任何表达式,例如,例如[style.width]="widthValue?(100/widthValue)+'%':'1%'"

标签: html css angular typescript


【解决方案1】:

使用class

<div [class]="'col-'+ widthValue"></div>

使用style.width

<div [style.width]="(widthValue/12)*100 + '%'"></div>

DEMO

【讨论】:

  • widthValue 持有什么?还有其他错误吗?
  • 不,没有与此相关的其他错误。 widthValue 只是一个数值。它实际上是网格大小。
  • 通过网格大小,您的意思是引导网格列大小为 12?
  • 是的,你可以这么说。实际上有一个变量你可以看到stripKpi。它是一个二维数组。我必须以矩阵形式显示这个数组。所以 6 个元素意味着 2 行和 3 列。在这种情况下,3 将是我的widthValue。这个逻辑已经写好了。所以现在我只想相应地计算宽度。
  • 我认为可以。我接受这个答案。非常感谢您的宝贵时间:-)
猜你喜欢
  • 1970-01-01
  • 2017-03-01
  • 2019-02-05
  • 2019-03-01
  • 2018-07-12
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
相关资源
最近更新 更多