3

I have an input like below, bounded with a reactive form control:

  <mat-form-field appearance="fill" floatLabel="always" fxFlex>
    <mat-label>My field</mat-label>
    <input
      matInput
      #input="matInput"
      [formControl]="amountControl"
      [errorStateMatcher]="customMatcher"
    />
    <mat-error *ngIf="amountControl?.invalid">{{ getErrorMessage$() | async }}</mat-error>
  </mat-form-field>

Now, after the user enters a value, the value needs to be formatted, possibly on blur or custom keyboard shortcut, filled back into the html input field, and updated into the bounded form control with the formatted value.

I was thinking of using pipes, but then, it seems to be useful only to change how a value is displayed, but not save it back to the backing formControl.

What would be the correct approach to do this?

1 Answer 1

3

I would do it this way:
HTML:

<input
          matInput
          #input="matInput"
          [formControl]="amountControl"
          [errorStateMatcher]="customMatcher"
          (blur) = "transform()"
 />

TS:

  amountControl = new FormControl('');
  transform(){
    let transformValue = this.amountControl.value - 5; // your pipe here
    this.amountControl.setValue(transformValue);
  }

The value will change as you type, but transformation will occur on blur, if you want the value to change only on blur, you can use this:

amountControl = new FormControl('', {updateOn: 'blur'});

EDIT: StackBlitz example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.