将字符串转换为数字角2单向绑定

Dev*_*per 3 angular2-template angular

将字符串转换为数字角2单向绑定

[longitude]="loc.location.lng">
Run Code Online (Sandbox Code Playgroud)

loc.location.lng是字符串,我需要将它们转换为number。但是仍然无法按我期望的那样工作。在插值中,它起作用了,但在这种情况下不起作用。谢谢

And*_*aru 6

你也可以通过尝试这个来强制演员:

[longitude]="+loc.location.lng"
Run Code Online (Sandbox Code Playgroud)


Adi*_*iii 5

创建一个函数,将值转换为float作为其位置并返回该值。

    ConvertString(value){
return parseFloat(value)
}
Run Code Online (Sandbox Code Playgroud)

调用模板中的函数

[longitude]="ConvertString(loc.location.lng)"
Run Code Online (Sandbox Code Playgroud)

  • 不要使用此方法,而应使用自定义管道。你不应该在 Angular 模板中使用函数调用 [为什么你不应该在 Angular 模板表达式中使用函数调用](https://medium.com/showpad-engineering/why-you-should-never-use-function-calls-in -角度模板表达式-e1a50f9c0496#:~:text=To%20avoid%20issues%2C%20it%20is,管道的%20input%20does%20not%20change) (2认同)