2

I know I've to use ngClass or ngStyle but I'm not able to figure out how to pass that value. Here is my code.

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>

I've to decide width of rows class dynamically in scss something like this:

strip.component.css

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

I could have used col-{{widthValue}} in HTML but no, I've been told that it has to be from the width property from css. Please help me. I'm not sure how to use ngClass here.

4
  • Use ngStyle to set the width dynamically. Commented Dec 2, 2020 at 11:11
  • you can use in the .html: [style.width]="(100/widthValue)+'%'" or [ngClass]="'col-'+widthValue" Commented Dec 2, 2020 at 11:11
  • @Eliseo, this didn't work. elements just crashed into each other as if the width was zero. :-( Commented Dec 2, 2020 at 11:14
  • you can use any expresion, like, e.g. [style.width]="widthValue?(100/widthValue)+'%':'1%'" Commented Dec 2, 2020 at 11:42

1 Answer 1

3

Use class

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

OR

Use style.width

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

DEMO

Sign up to request clarification or add additional context in comments.

5 Comments

What does the widthValue hold? Is there any other error?
No there's no other error related to this. widthValue is just a numeric value. It is actually the grid size.
By grid size, you mean the bootstrap grid column size out of 12?
Yes you can say that. Actually there is a varibale you can see stripKpi. It is a 2D array. I've to display this array in matrix form. So 6 elements mean 2 rows and 3 columns. In this case 3 will be my widthValue. this logic has already been written. So now i just want width to be calculated accordingly.
i think this will do. I'm accepting this answer. thanks a lot for your time :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.