Angular6でtypescriptコードからcssに値を渡す方法

Dec 02 2020

使用するngClass必要ngStyleがあることはわかっていますが、その値を渡す方法がわかりません。これが私のコードです。

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でクラスの幅を動的に決定する必要があります

strip.component.css

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

col-{{widthValue}}HTMLで使用することもできましたが、いいえ、cssのwidthプロパティからのものである必要があると言われました。私を助けてください。ここでngClassの使い方がわかりません。

回答

1 Vishnudev Dec 02 2020 at 18:13

使用する class

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

または

使用する style.width

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

デモ