Search code examples
angulartypescriptangular-material2mat-form-field

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!


Solution

  • 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