Home > Blockchain >  ngModelChange in Angular not working when input box changes from somewhere else using two way data b
ngModelChange in Angular not working when input box changes from somewhere else using two way data b

Time:12-27

HTML

          <div >
              <label for="usr"><b>Username:</b></label>
              <input type="text" (keyup)='keyUp.next($event)' (ngModelChange)="disableEnableLogin()" [ngModel]="getUsername"  id="usr">
          </div>
          <div >
              <label for="pwd"><b>Password:</b></label>
              <input type="password" (keyup)='keyUp.next($event)' (ngModelChange)="disableEnableLogin()" [ngModel]="getPassword" 
                  id="pwd">
          </div>
      </div>

TS

disableEnableLogin() {
    console.log('hi');
}

DisableEnableLogin is not getting fired on (ngModelChange)

CodePudding user response:

You should used ngModelChange with $event. Btw your solution is working for me, but there is some errors with keyup. So removing the keyup should also work on your side.

HTML:

 <div>
  <div >
    <label for="usr"><b>Username:</b></label>
    <input
      type="text"
      (ngModelChange)="disableEnableLogin($event)"
      [ngModel]="getUsername"
      
      id="usr"
    />
  </div>
  <div >
    <label for="pwd"><b>Password:</b></label>
    <input
      type="password"
      (ngModelChange)="disableEnableLogin($event)"
      [ngModel]="getPassword"
      
      id="pwd"
    />
  </div>
</div>

TS:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  public disableEnableLogin(newValue: any){
    console.log(newValue);
  }
}

And maybe keep in mind that there are two solutions.

(ngModelChange) = "disableEnableLogin()" will fire before the value bound to [(ngModel)] = "value" is changed

while the (change) = "disableEnableLogin()" will fire after the value bound to [(ngModel)] = "value" is changed

I'm adding a link to the plunker if you want to try it directly and change something.

https://stackblitz.com/edit/angular-display-code-snippets-in-html-page-dek3ce?file=src/app/app.component.ts

I hope it helped.

CodePudding user response:

Basically, ngModelChange will trigger when the model value changes and change method triggers when value changes and leave the input focus.

  • Related