这个问题在angular中使用确实有些费劲,网上所能查得到的资料有限,所以走了一些弯路,不过好在解决了。
下面直接代码演示
html文件:
首先要动态绑定函数,注意,如果你想使用[ngStyle]直接在行内使用calc和变量,大可以试试,反正能想到的我都使用了,都没解决,如果你有好的方法,也可以私信一下我哟!
<div [ngStyle]="add()" >这是一个盒子</div>
其次在ts文件:
import { Component } from '@angular/core';
@Component({
selector: 'app-goods',
templateUrl: './goods.component.html',
styleUrls: ['./goods.component.less']
})
export class GoodsComponent {
public m: number = 2;
public n: number = 3;
add1() {
const style = {
"width": calc(50, this.m) + "vw",
"height": calc(50, this.n) + "vh",
"backgroundColor": "blue"
};
return style;
}
}
// 注意css3的特性calc函数不能直接在add1函数中直接运算,会报错,
// 此处定义一个方法函数进行想要的运算,调用到上面的函数中,就能达到想要的计算效果,目前这是我研究出来能够实现一些业务逻辑的方法
function calc(x: number, y: number) {
return x / y
}
效果如下: