DAG
DAG

Reputation: 2630

Angular 6 custom Input component

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.

Upvotes: 2

Views: 2786

Answers (1)

Augustin R
Augustin R

Reputation: 7819

Replace [value] by a ngModel :

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

Stackblitz example

Upvotes: 3

Related Questions