[Fixed] Very simple ngModel example


I have a simple form

<form role="form" (submit)="login()">
  <input type="text" name="username" id="username" required="required" [ngModel]="credentials.username"/>
  <input type="password" name="password" id="password" required="required" [ngModel]="credentials.password" />
  <button type="submit">Sign in</button>

and a component ts.

export class LoginComponent implements OnInit {
  credentials = {username: '', password: ''};
  constructor(private loginService: LoginService, private http: HttpClient, private router: Router) { }
  ngOnInit() { }
  login() {
    this.loginService.authenticate(this.credentials, () => {
    return false;


authenticate(credentials, callback) {
  const headers = new HttpHeaders(credentials ? {
   authorization : 'Basic ' + btoa(credentials.username + ':' + credentials.password)
  } : {});

My problem is that the credentials are always ''. Shouldn’t the ngModel update these values automatically?


You should use [(ngModel)] to set values like this –

<input type="text" name="username" id="username" placeholder="Username" required="required" [(ngModel)]="credentials.username"/>
  <input type="password" name="password" id="password" placeholder="Password" required="required" [(ngModel)]="credentials.password" />

As of now, you are using [ngmodel] which is just attribute binding to set value into your DOM and display it back.

But if you want to update value from view part you should use two way data binding [(ngModel)]

Leave a Reply

(*) Required, Your email will not be published