Convert number to degrees in ngStyle using Angular 8

南笙酒味 提交于 2019-12-03 00:49:45

问题


{{result.percentage}} gives me a number from 0 to 100.

If I get 25, I want it to convert to -45 degrees or if I get 0, I want it to convert to -90 degrees or if I get 75, then it gets converted to 45 degrees.

[ngStyle]="{'transform': 'rotate(' + result.percentage + 'deg)'}"

Current, this gives an output style="transform: rotate(25deg);" which I want to convert to style="transform: rotate(-45deg);"

How do I go about this?

FYI, I need to bind the data of this speedometer: https://jsfiddle.net/bcgzrdfL/


回答1:


Looks like you need a math whiz, not a framework expert, however I'm going to take a shot at an answer:

[ngStyle]="{'transform': 'rotate(' + ((result.percentage * 1.8) - 90) + 'deg)'}"



回答2:


Something like this?

html

[ngStyle]="{'transform': 'rotate(' + convertedPercentage + 'deg)'"

component

get convertedPercentage() {
  return (this.result.percentage * 1.8) - 90;
}



回答3:


from a performance perspective, you're better off calculating the value only when it needs to be calculated, rather than doing the math in template.

styles = {}

setStyles(percentage) {
   this.styles = {
     'transform': 'rotate(' + ((percentage * 1.8) - 90) + 'deg)'
   }
}

call that when you get / assign your result or change your percentage, then use in template like:

[ngStyle]="styles"

the way you have it now, the degrees get calculated on every change detection cycle instead of only when they need to. This is a bad practice that will lead to poor app performance if you keep doing it.



来源:https://stackoverflow.com/questions/59061404/convert-number-to-degrees-in-ngstyle-using-angular-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!