Angular 参数似乎对 Style 没有影响

Angular parameter seems to have no effect in Style

我有以下 Angular 模板 StackBlitz Example:

<div class="progress">
  <div class="complete" style="width: {{progress}}%">&nbsp;</div>
</div>

<p>{{progress}}%</p>

代码 width: {{progress}}% 不起作用,但如果我将其替换为 width: 60% 则可以。

并且代码 <p>{{progress}}%</p> 呈现正确的值 ...

组件代码为:

export class ProgressComponent implements OnInit {

  @Input() current: any;
  @Input() minimum: any;
  @Input() maximum: any;

  progress: number;

  ngOnInit() {
    this.progress = 100 * (this.current - this.minimum) / (this.maximum - this.minimum);
  }

}

知道我错过了什么吗?

像这样:

<div class="progress">
    <div class="complete" [style.width.%]="progress">&nbsp;</div>
</div>

你可以试试:

 <div class="complete" [ngStyle]="{width: progress + '%'}">&nbsp;</div>

您需要在 Angular 2 模板中绑定内联样式。 以下是如何绑定单个样式值,例如:

<p [style.background-color]="'red'">
  my background is red
</p>

所以,您更新后的代码将是 -

<div class="progress">
  <div class="complete" [style.width.%]="progress">&nbsp;</div>
</div>

<p>{{progress}}%</p>

另外: 你也可以在 %.

的地方使用 px, em

你可以在这里设置条件。

<p [style.font-size.px]="isItGreaterThan60 ? '60' : '16'">
  I am some text
</p>

单身属性。如果我们需要应用多种样式怎么办? [ngStyle]是救星

[ngStyle] for multiple styles

<p [ngStyle]="{ 'background-color': 'red', 'font-size': '30px', 'width':'60%' }">
 I am multiple styles
</p>

可以在html中写css,也可以在组件ts文件中加一个属性,在html中使用。像这样 -

<p [ngStyle]="myStyles">
    I am for multiple styles.
</p>

'myStyles' 是您组件的一个对象。所以,在你的组件中,

myStyles = {
 'background-color': 'red',
 'font-size': '30px',
 'width': '60%'
}

您还可以使用方法和 return 样式对象。然后使用 html 标签内的方法名称。像这样 -

<p [ngStyle]="getMyStyles()">
    my styles comes from a function
</p>