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

There are 2 best solutions below

2
On BEST ANSWER

As @MoxxiManagarm said, the MatFormField is only something that wrap an input, which can then be a text, textarea, select ..., so in your case you are talking about input. So then you can easily include the solution to your input in your MatFormField.

With a simple (keyup.enter) directive, you can bind your input to a method when the user use the Enter Key.

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

Then on your method, to be sure you want to do an operation as Excel does, check if the first character is an equal.

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 is a stackblitz

0
On

MatFormField is only a wrapper component. I guess we are speaking about an input.

You can react on the input event and simply override the content

<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;
  }