Search code examples
angularangular-forms

Getting error in fetching value of template driven Angular form


In the register function I am getting the error in storing the value of the form control .

using "let firstname" , "let lastname" , "let email" I am getting error [tslint] Identifier 'firstName' is never reassigned; use 'const' instead of 'let'. (prefer-const)

Using debugger I am getting error [tslint] Use of debugger statements is forbidden (no-debugger)

Also in the console I am getting error Cannot read property 'value' of undefined

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

@Component({
  selector: 'app-temp-driven',
  templateUrl: './temp-driven.component.html',
  styleUrls: ['./temp-driven.component.css']
})
export class TempDrivenComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  register(regForm: any) {
    debugger;
    let firstName =  regForm.control.firstname.value;
    let lastname = regForm.control.lastname.value;
    let email = regForm.control.email.value;

    alert(firstName);
   console.log(regForm);

  }

}

Html ->

<div class="container">
  <div class="row">
    <div class="form-bg">
      <form #regForm ='ngForm' (ngSubmit) ="register(regForm)">
       <h2 class="text-center"> Registeration Form </h2>
      <br/>
      <div class="form-group">
       <input type="text" class="form-control" placeholder="First Name" name="firstname" ngModel>
      </div>  


      <div class="form-group">
          <input type="text" class="form-control" placeholder="last Name" name="lastname" ngModel>
         </div>  


      <div class="form-group">
          <input type="text" class="form-control" placeholder="Eamil Id" name="email" ngModel>
         </div>  

          <br/>

          <div class="align-center">
            <button type="submit" class="btn btn-primary" id="register"> Register </button>
          </div>
          </form>   
      </div>  
  </div>
</div>

Solution

  • Cannot read property 'value' of undefined error

    is because

    You have written controls as control. Replace that, It should work.

    register(regForm: any) {
        debugger;
        let firstName =  regForm.controls.firstname.value;
        let lastname = regForm.controls.lastname.value;
        let email = regForm.controls.email.value;    
       alert(firstName);
       console.log(regForm);    
    }
    

    You could ignore the first warning, or it is also fine if you change let to const, because you are not modifying them after they are set.