0

I'm trying to solve this thing I've got in my app:

I've a simple number input (not form, just a dummy input). I've created a "validation" inside my component's class. The problem is that if I change the input's value in code, first time the validator changes the value, but the second or more time the change isn't reflected in DOM. Here is a stackblitz example.

In my example app I have a really simple set-up:

app.component.html

<input type="number" [value]="inputValue" (change)="onInputChange($event.target.value)">

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public inputValue: number = 0;

  public onInputChange(event: number | string): void {
    const val = Number(event);
    if (val > 100) {
      this.inputValue = 100;
    }
  }
}

Steps:

  • change the value to 200 and press enter
  • since is larger than 100 the validator changes the input value to 100
  • change the value to 200 again and press enter
  • the value in DOM stays 200 instead of 100

My guess here is, that since second time the value of inputValue doesn't changes, the DOM doesn't got re-rendered. But if I trigger change detection manually, nothing happens.

Any idea guys?

Runtime Terror
  • 6,242
  • 11
  • 50
  • 90

1 Answers1

1

If you don't want to use ngModel, because you don't want to load the FormsModule, you can use the target input straight:

public onInputChange(input: HTMLInputElement): void {
  const val = Number(input.value);
  if (val > 100) {
    this.inputValue = 100;
    input.value = this.inputValue.toString();
  }
}

stack

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149