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

I am new to the Angular. I want to type =100+5 or =8*5/2 inside the mat form field and it calculate and display the result inside the mat form field itself when I press enter key. I am unsure how to handle these equation inside the MatFormField. Please help

Thanks in Advance!

2 ответа

Решение

Как сказал @MoxxiManagarm, MatFormField - это только то, что обертывает ввод, который затем может быть текстом, текстовым полем, выбором..., поэтому в вашем случае вы говорите о вводе. Таким образом, вы можете легко включить решение в свой ввод в свой 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"
  }
}

Вот стекблиц

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;
  }
Другие вопросы по тегам