1

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?

AT82
  • 71,416
  • 24
  • 140
  • 167
theGhostN
  • 342
  • 7
  • 20

1 Answers1

6

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>
AT82
  • 71,416
  • 24
  • 140
  • 167
  • You removed ngcontrols. Then what is the use of ngcontrol ? – theGhostN May 31 '17 at 05:04
  • `ngControl` would have been old syntax, prior to RC4 version when hastly googled... :) https://www.barbarianmeetscoding.com/blog/2016/07/15/updating-your-angular-2-app-to-use-the-new-forms-api-a-practical-guide/ – AT82 May 31 '17 at 09:48