[Fixed] Angular two way binding is not working [(NgModel)]

Issue

In angular code trying 2 way binding using model. But encountered error message while loading the page.
ErrorMessage: Cannot read property ‘username’ of undefined at RegisterComponent_Template (register.component.html:6).

register.html

      <form #registerForm="ngForm" (ngSubmit)="register()" autocomplete="off">
      <h2 class="text-center text-primary">SignUp</h2>
      <hr>
      <div class="form-group">
      <input type="text" class="form-control" name="username" 
      [(ngModel)]="model.username" placeholder="username">

       </div>
       <div class="form-group">
      <input type="text" class="form-control" name="password" [(ngModel)]="model.password" 
      placeholder="password">
      <p> You entered {{model.password}}</p>
     </div>

     <div class="form-group">
     <button class="btn btn-success mr-2" type="submit">Register</button>
     <button class="btn btn-default mr-2" type="button" (click)="cancel()">Cancel</button>
     </div>
    </form>

register.ts

  import { Component, Input, OnInit, Output,EventEmitter } from '@angular/core';
import {FormsModule} from '@angular/forms';
import { AccountService } from '../_services/account.service';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
@Output () cancelRegister = new EventEmitter();
  constructor(private accountService: AccountService) { }
  model:any;

  ngOnInit(): void {

    
  }


  register() {
    this.accountService.register(this.model).subscribe(response => {
      console.log(response);
      this.cancel();
    }, error => {
      console.log(error);
    })
  }
  cancel() {
    this.cancelRegister.emit(false);
  }

}

Solution

The error is due to the ngForm variable model not being initialized.
In your ngOnInit try initializing it like

this.model = {  userName: '', password: '' };

Leave a Reply

(*) Required, Your email will not be published