Let's create a very simple component that just renders a form. In our main index.html file we are going to define a new html element called <my-form>
.
index.html
<my-form>Loading...</my-form>
Then we are going to create a boot file to load the main component of our application.
app/boot.ts
import {bootstrap} from '@angular/platform-browser-dynamic';
import {MyForm} from './my-form.component';
bootstrap(MyForm);
In order to render the <my-form>
element, we need to define a new component.
app/my-form.component.ts
import {Component} from '@angular/core';
import {bootstrap} from '@angular/platform-browser-dynamic';
@Component({
selector: 'my-form',
templateUrl: 'app/my-form.component.html'
})
export class MyForm {}
And finally, we'll define the component's template as a separate file for easier visualization.
app/my-form.component.html
<form novalidate>
<div>
<label for="email">Email:</label>
<input type="email" id="email">
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password">
</div>
<button type="submit">Register</button>
</form>
We are using the attribute
novalidate
in our form to prevent the browser from performing its built-in validation for the email field. We are going to create our own validation using Angular in a following section.
At this point, if we click the submit button nothing happens because we defined a standard HTML form, not an Angular 2 form. To fix that, we need to tell our component to upgrade our form using the NgForm
directive which will give us access to new properties and event bindings on our form to interact with it.
app/my-form.component.ts
// ...
import {FORM_DIRECTIVES} from '@angular/common';
@Component({
// ...
directives: [FORM_DIRECTIVES]
})
export class MyForm {}
Notice that we didn't include the NgForm
directly, instead we included FORM_DIRECTIVES which is an array of all the directives used in forms, including NgForm
. To see all the directives included in this array, check the source code.
Because we now have an Angular 2 form, we can listen to the ngSubmit
event which is triggered whenever the form is submitted.
app/my-form.component.html
<form (ngSubmit)="onSubmit()">
We are telling our component that when the form is submitted, the onSubmit
method of our component will be invoked, so let's define this method.
app/my-form.component.ts
@Component({
// ...
})
export class MyForm {
onSubmit() {
console.log('Form submitted!');
}
}
Now when we click the submit button, we can see the message "Form submitted!" outputted onto the DOM.