如何将属性绑定到Angular 2中的样式宽度像素?

时间:2016-12-02 10:44:52

标签: html css angular

我正在使用Angular 2.0并且我已经编写了以下代码:

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

我也试过

<div [ngStyle]="{'width.px': width}">some texts </div>

export class MyComponent
{
 width: number = 150;
}

但它并没有将宽度绑定到div元素。

我使用的是最新版本的Angular 2.0。

我做错了什么?

5 个答案:

答案 0 :(得分:34)

适合我的工作

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'
  }
}

答案 1 :(得分:10)

这对我有用:

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

答案 2 :(得分:2)

检查一次如下:

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

export class MyComponent
{
 width: number = 150;
}

答案 3 :(得分:0)

对于像素单位

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

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

其他CSS单位

<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>

组件

export class MyComponent
{
   width: number = 80;
}

答案 4 :(得分:0)

您的代码是正确的。只需使用检查元素检查 div 的样式。

F12 或按 ctrl + shift + i 打开检查。转到元素选项卡并找到您的 div 并检查它的 CSS 属性,宽度已应用。

例如:

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

否则为您的 div 标签添加背景颜色,以便您可以轻松看到它。

.html 文件(模板)

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

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

.ts 文件(组件)

export class MyComponent
{
    width: number = 150;
}