我如何从 Mat 表单字段计算数学方程式,该字段的公式类似于 excel 等号使用 Angular material

How can I calculate the math equation from a Mat form field that formulates like an excel with equal symbol using Angular material

我是 Angular 的新手。我想在 mat 表单字段中键入 =100+5 或 =8*5/2,当我按下 enter 键时,它会计算并在 mat 表单字段本身内显示结果。我不确定如何在 MatFormField 中处理这些方程式。请帮助

提前致谢!

MatFormField 只是一个包装组件。我想我们正在谈论输入。

您可以对输入事件做出反应并简单地覆盖内容

<input (keydown.enter)="solveEquation($event)" />
  solveEquation($event) {
    const element = $event.target;
    element.value += `=${this.solve(element.value)}`
  }

  private solve(equation: string): number {
    // any logic to solve the string equation
    return 111;
  }

正如@MoxxiManagarm 所说,MatFormField 只是包装输入的东西,然后可以是文本、textarea、select ...,所以在您的情况下,您正在谈论输入。因此,您可以轻松地将解决方案包含在您的 MatFormField 中。

使用简单的 (keyup.enter) 指令,您可以在用户使用 Enter 键时将输入绑定到方法。

<input type="text" (keyup.enter)="onEnter($event)">

然后在你的方法上,为了确保你想要像 Excel 那样进行操作,检查第一个字符是否相等。

onEnter(event){
  const value = event.target.value
  if (value[0] == "="){
    event.target.value = eval(value.substring(1)) // Here you get only the operation to evaluate it without the first "equal"
  }
}

Here 是一个 stackblitz