Building Forms in Angular 2
In the previous sections we looked at input and output with our Angular 2 components
- Input: via attributes and properties
- Output: via events which we can listen to
This means we can now interact with forms.
An <input /> DOM node will emit many different events when our user interacts with it, including:
- keyup - when the user presses a key
- focus - When the user enters the field
- blur - When the user leaves the field
- input - When the value property changes
We can bind to any of these and have our update events fire when the event is triggered.
The input event
The most interesting of these is the input event. This fires whenever the value attribute changes.
<input on-input="onInput($event)" />
We can deal with this event like so:
.Class({
constructor: function() {
var vm = this;
vm.onInput = function(evt) {
this.catName = evt.target.value;
}
// this.username = new ng.common.Control('username')
}
});
Initialising the value:
We might want to initialise the value of catName. We can do this in our template using simple property binding, like so:
<input [value]="catName" on-input="onInput($event)" />
We might then output this value somewhere using curlies:
{{catName}}
Exercise - Two way binding
Create a little UserEdit component now. Put a form in it that will allow us to edit a user.
Bonus Points
For bonus points, allow the user to be passed in from the parent template.
NgModel
NgModel is a directive. We haven't seen any directives yet. A directive is just a component which doesn't have it's own template. Instead it modifies the template of the component or element it is applied to.
We will build a directive of our own in a later exercise.
The NgModel directive creates all of this data binding for us. It will bind a value and add an input listener.
<input [(ngModel)]='catName' />
Notice the [()] brace combo. This shows that we are binding a property, to the return value of the event listener. It's a two way binding.
Exercise - ngModel
Re-implement the above using 2 way binding.
Binding to submit
We can bind to the (submit) event of a form to have something happen when we submit. This is better than binding to the (click) event of the button, because there are ways to submit a form other than clicking the button, for example the user might press enter on an input element.
<form (submit)="onSubmit()">
<button>Go!</button>
</form>
If we have used ngInput to bind our inputs, we can then use this data to update a model.
Hard Exercise - Update the user
Extend your user userEditor component, such that the user is only updated when we click submit.