Angular 模板文字:将字符串转换为数字后的加法只是连接

Angular Template Literals : Addition after converting string to number becoming just concatenation

我正在开发基于 Angular 4 的计费应用程序。我必须对我应用的逻辑进行更改。但是当我进行更改时,一切都坏了。我深入检查,发现在模板中将 String 转换为 Integer 后的加法只是连接。

正常JavaScript,

100 + +"28" 

将是128

console.log(100 + +"28");

但在 Angular 模板文字中,它变为 10028

这3种方式我都试过了

{{100 + +"28"}}

{{100 + (+"28")}}

{{(100 + (+"28"))}}

但是两次都是 3 次,它产生 10028。

我无法将其存储在变量中并显示,因为我正在使用 ngFor

我的原始代码中的 MCVE 是

<div class="row bill-entry" data-id="" *ngFor="let i of item">
  <div class="col-md-4 col-sm-4 col-lg-4">
    {{i.itemName}}
  </div>
  <div class="col-md-2 col-sm-2 col-lg-2">
    {{i.qty}}
  </div>
  <div class="col-md-3 col-sm-3 col-lg-3">
    <div class="row price">
      <div class="col-md-4 col-sm-4 col-lg-4">
        <div class="over-price">{{ (((i.qty * i.ind_price) / (100 + (+i.gst))) * 100).toFixed(2) }}
                                                             ^^^^^^^^^^^^^^^^^^  -> Problem
        </div>
      </div>
    </div>
  </div>
</div>

这是我在其中重现此问题的minimal plunker


注:

GST 是印度的商品及服务税。产品的最终价格包含 GST。客户将输入最终价格。该应用程序应该找到不含 GST 和 GST 的价格。也就是说,如果产品价格为 100.00 印度卢比,商品及服务税为 28%,那么它的实际价格为 78.13 印度卢比,商品及服务税为 21.87 印度卢比。客户只会输入100。我必须计算其他2个值并将其打印在Bill中。

我只能假设...

i.gst 是数据中的字符串,这意味着您需要在控制器/组件上使用其他方法将其转换为整数或浮点数。

我已经使用了你的 plunker 并添加了一个数据 属性 以及相应的转换方法

//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 *ngFor="let i of data">Hello {{100+getNumber(i.gst)}}</h2>
      <h2>Hello {{100+ (+"28")}}</h2>
      <h2>Hello {{(100+ (+"28"))}}</h2>
    </div>
  `,
})
export class App {
  name:string;

  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  // data array
  data = [
    {gst: "28"},
    {gst: "32"}
  ];

  // method to convert string to float
  getNumber(string) {
    return parseFloat(string);
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}