53

I'm using Angular 2 and I've written the below code:

<div [style.width.px]="width">some texts </div> 

I've also tried:

<div [ngStyle]="{'width.px': width}">some texts </div> export class MyComponent { width: number = 150; } 

But it doesn't bind the width to the div element.

What am I doing wrong?

0

6 Answers 6

69

Works fine for me

Plunker example

@Component({ selector: 'my-app', styles: [`div { border: 3px solid red; }`] template: ` <div> <h2>Hello {{name}}</h2> <div [style.width.px]="width">some texts </div> </div> `, }) export class App { name:string; width: number = 250; constructor() { this.name = 'Angular2' } } 
Sign up to request clarification or add additional context in comments.

1 Comment

{{ and }}. [...] and {{...}} are never used together. [...]="xxx" already defines that xxx is an expression. Try [style.width] ="'calc(100% - ' + myWidth + ')'"
24

For pixel unit

<div [style.width.px]="width"> Width Size with px</div> 

Or

<div bind-style.width.px="width"> Width Size with px</div> 

Other CSS units

<div [style.width.em]="width"> Width Size with em</div> <div [style.width.pt]="width"> Width Size with pt</div> <div [style.width.%]="width"> Width Size with %</div> 

Component

export class MyComponent { width: number = 80; } 

Comments

23

This worked for me:

<div [style.width]="paymentPerc+'%'"> Payment Recieved</div> 

Comments

8

Check with same as below once:

<div [style.width]="width+'px'">some texts </div> export class MyComponent { width: number = 150; } 

Comments

3

Sorry for the late answer. Most of the answers are good enough.

Let me add that if you want to use px and % at the same time, then you can do something like this;

<div [style.width]="myCondition == true ? MyHeightVariable+'px' : '33.33%' " > </div> 

Or if you only want to set it in px;

<div [style.width.px]="myCondition == true ? MyHeightVariable : '33.33' "></div> 

Or if you only want to set it in %;

<div [style.width.%]="myCondition == true ? MyHeightVariable : '33.33' "></div> 

Comments

0

Your code is correct. Just check styles of your div using inspect element.

Press F12 or hit ctrl + shift + i to open Inspect. Go to Elements Tab and find you div and check it's CSS properties, width is applied.

for Example:

element.style { background-color: pink; width: 150px; } 

Otherwise add background color to your div tag so It will easily visible to you.

.html file (template)

<div [style.width.px]="width" style="background-color:pink"> some text </div> 

Or

<div [ngStyle]="{'width.px': width}" style="background-color:pink"> some text </div> 

.ts file (component)

export class MyComponent { width: number = 150; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.