krisyupher
krisyupher

Reputation: 13

input not update view ngmodelchange

I want to remove the letters and leave only numbers, the validation is fine but the input view does not update correctly. the variable "quantity" does change its value and I can show it below with
<p> {{quantity}} </p>

button-add.component.html

<input
      [ngModel]="quantity"
      (ngModelChange)="quantity = changeQuantity($event)"
    />
    <p> {{quantity}} </p>

button-add.component.ts

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

@Component({
  selector: 'button-add-button',
  templateUrl: './button-add.component.html',
  styleUrls: ['./button-add.component.scss'],
})
export class ButtonAddComponent implements OnInit {
  quantity: number = 10;
  constructor() {}

  public changeQuantity(cant: string) {
    return parseInt(cant.replace(/[^0-9]+/g, ''));
  }
}

Upvotes: 0

Views: 790

Answers (1)

Amit Bisht
Amit Bisht

Reputation: 5136

The way you are using the ngModel is incorrect, you need to correct that first, after that instead of model change do It on the keyup event, kindly refer to below code

<input [(ngModel)]="quantity" (keyup)="changeQuantity($event)" />
<p> {{quantity}} </p>  

Also instead of directly setting value in your .html keep it in your .ts and reassign it to quantity, refer to below code

public changeQuantity(cant: any) {
  this.quantity = parseInt(cant.target.value.replace(/[^0-9]+/g, ''));
}  

Please find the behaviour of various events which will help you to decide when to trigger changeQuantity()

  • keypress or input: on every next keystroke your value will get updated
  • change: outside click of control will trigger this
  • keyup: reflects immediately but it will show a slight flicker

For better clarification on events, refer best bet event

Upvotes: 0

Related Questions