简体   繁体   中英

ngModelChange in Angular not working when input box changes from somewhere else using two way data binding

HTML

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

TS

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

DisableEnableLogin is not getting fired on (ngModelChange)

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 class="form-group">
    <label for="usr"><b>Username:</b></label>
    <input
      type="text"
      (ngModelChange)="disableEnableLogin($event)"
      [ngModel]="getUsername"
      class="form-control"
      id="usr"
    />
  </div>
  <div class="form-group">
    <label for="pwd"><b>Password:</b></label>
    <input
      type="password"
      (ngModelChange)="disableEnableLogin($event)"
      [ngModel]="getPassword"
      class="form-control"
      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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM