0

I'd like to format the value inside the textbox with a percent pipe, so that 0.42 shows up as 42%. I'd like to do this initially, as well as when the user changes the value.

public myFormGroup: FormGroup = new FormGroup({
    myNumber: new FormControl(0.42)
});
<div [FormGroup]="myFormGroup">
  <input formControlName="myNumber">
</div>

But I don't see a way to do this. Initial google searches produced results like this one: How to use pipes in Angular 5 reactive form input, which seems a bit overly complicated for such a simple use case.

Thanks.

FunkMonkey33
  • 1,956
  • 2
  • 16
  • 24

1 Answers1

1

Transform the value (using pipe) during form initialization and also when the value changes

 this.form = this.fb.group({
      myNumber: [this.percentPipe.transform(0.42)]
    })
    
  setValue(): void {
    const input = this.form.controls.myNumber.value;
    this.form.controls.myNumber.setValue(this.percentPipe.transform(input));
  }
<form [formGroup]="form">
  <input type="text" formControlName="myNumber" (change)="setValue()">
</form>
Sony
  • 26
  • 2