2

I have created a custom input component in Angular 6. This input component can be either of type text or number. If it's a number, I need to validate for min and max values.

The validation works, but the value of the input does not get updated on the second time. The model updates tho.

The component looks like that:

<input [type]="type" [min]="min" [max]="max" (keyup)="change($event.target.value)" [value]="value">

That is ma change event on keypress:

change(value: any): void {
    if (this.max) {
      if (value > this.max) {
        this.value = this.max;
        this.valueChange.emit(this.value);
        return;
      }
    }

    if (this.min) {
      if (value < this.min) {
        this.value = this.min;
        this.valueChange.emit(this.value);
        return;
      }
    }

    this.value = value;
    this.valueChange.emit(this.value);
  }

That is my complete InputComponent

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';

@Component({
    selector: 'app-custom-input',
    templateUrl: 'input.component.html',
    styleUrls: ['./input.component.scss']
})
export class InputComponent implements OnInit {
    @Output() valueChange = new EventEmitter();

    @Input() value: any = null;
    @Input() type = 'text';
    @Input() min: number;
    @Input() max: number;

    constructor() {}

    ngOnInit() {}

    change(value: any): void {
      if (this.max) {
        if (value > this.max) {
          this.value = this.max;
          this.valueChange.emit(this.value);
          return;
        }
      }

      if (this.min) {
        if (value < this.min) {
          this.value = this.min;
          this.valueChange.emit(this.value);
          return;
        }
      }

      this.value = value;
      this.valueChange.emit(this.value);
    }
}

Why is the input value not being updated? The model updates properly. If I debug the code I see that this.value is the value expected, but in the DOM it's not.

enter image description here

The image above shows the value in red circle should also be in the input value. As you can see, the model is correct, but the input value is not updating.

1 Answer 1

3

Replace [value] by a ngModel :

<input [type]="type" [min]="min" [max]="max" (keyup)="change($event.target.value)" [(ngModel)]="value">

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.