角度参数似乎对样式没有影响

时间:2019-01-28 11:26:09

标签: angular angular6 angular7

我有以下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);
  }

}

知道我缺少什么吗?

3 个答案:

答案 0 :(得分:4)

类似这样的东西:

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

答案 1 :(得分:2)

您可以尝试:

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

答案 2 :(得分:0)

您需要在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]用于多种样式

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

您还可以使用方法并返回样式对象。然后在html标记内使用方法名称。像这样-

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