Search code examples
angulartypescriptangular6angular-forms

Angular 6 Form - Mutate Value after ValueChanges


My goal is to mutate the name value after every value change. (in my case to remove all unnecessary spaces in the name value) I have a simple form:

this.form = this.fb.group({
    name: new FormControl(''),
    description: new FormControl(''),
});

HTML

<form [formGroup]="form">
    <input formControlName="name">
    <input formControlName="description">
</form>

Logic

this.form.valueChanges.subscribe(data => {
    const newName = 'some mutated name';
    this.form.patchValue({
        ...this.form.value,
        name: newName,
    });
    // triggers an infinite loop
});

...but this triggers an infinite loop enter image description here


Solution

  • You could try using the keyup event on the input:

    <input (keyup)="onKey($event)">

    Then do your string modification in the like this

    onKey(event: any) { // something like this // check event.target.value for the values and modify as needed this.name = newName; }