angularangular2-formsng-submit

angular 2 - ngForm.value does not have ngControl members


I have the following form :

import { Component } from '@angular/core'

@Component({
    selector: 'form1',
    template: `
      <div >
        <form (ngSubmit)="onSubmit(f)" #f="ngForm">
           <input ngControl="email" type="text" id="mail" required>                              
           <input ngControl="password" type="text" id="password" required>
           <input ngControl="confirmPass" type="text" id="confirmPass" required>                                
           <button type="submit">Submit </button>
        </form>
      </div>                    `
})
export class Form1Component{
    onSubmit(form:any){
      console.log(form.value);
    }
}

The problem is form.value has only an empty object and there is no sign of values of ngControl directives. Am I missing something?


Solution

  • Defining a name attribute in forms is a requirement, from angular.io docs:

    Internally, Angular creates FormControl instances and registers them with an NgForm directive that Angular attached to the <form> tag. Each FormControl is registered under the name you assigned to the name attribute.

    So without name it's not considered as a form control. Also we need to use ngModel:

    The NgForm directive supplements the form element with additional features. It holds the controls you created for the elements with an ngModel directive and name attribute

    So all in all, your template should look like this:

    <form (ngSubmit)="onSubmit(f)" #f="ngForm">
      <input type="text" id="mail" name="email" ngModel required>                              
      <input type="text" id="password" name="password" ngModel required>
      <input type="text" id="confirmPass" name="confirmPass" ngModel required>                                
      <button type="submit">Submit </button>
    </form>