0

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!

Muthukani K
  • 151
  • 1
  • 15
  • Have you checked out on using a `directive` to achieve this? – Owen Kelvin Sep 02 '20 at 10:01
  • @Muthukani k just use function https://stackoverflow.com/questions/2276021/evaluating-a-string-as-a-mathematical-expression-in-javascript –  Sep 02 '20 at 16:45

2 Answers2

3

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

Alexis
  • 1,685
  • 1
  • 12
  • 30
  • i was thinking about split and then checking arithmetic operators on condition base and then perform calculation again using split function and so on. `eval` is new addition in my knowledge. thanks – Farhat Zaman Sep 02 '20 at 10:28
  • 1
    Yes with eval it will automatically do the job for you. Your welcome – Alexis Sep 02 '20 at 10:29
2

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;
  }
MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43