At this point our component doesn't know how to get the values introduced in the form's fields. To do that we need a way to pass an instance of the form when calling the onSubmit
method on the template.
The NgForm
directive, besides defining a new ngSubmit
event on the form, is also creating and exporting an instance of the NgForm
directive, called unsurprisingly ngForm
, to be used as a local template variable.
app/my-form.component.html
<form #regForm="ngForm" (ngSubmit)="onSubmit(regForm)" novalidate>
Here we are naming regForm
("registration form") our local reference to the NgForm
directive instance and passing it to our component in the onSubmit
method. It's now time to update the component method to read the values of our form.
app/my-form.component.ts
// ...
import {NgForm} from '@angular/common';
@Component({
// ...
})
export class MyForm {
onSubmit(regForm: NgForm) {
console.log(regForm.value);
}
}
Even if we fill both inputs and click the submit button, we get an empty object in the console. To understand what's happening we should review some core concepts about forms in Angular 2 before moving on with our code example.
<iframe class="no-pdf" style="width: 100%; height: 300px" src="https://embed.plnkr.co/fo4ZXG9IAcEqtYgT6dJs" frameborder="0" allowfullscren="allowfullscren"></iframe>