1.2 How to Code Forms in Angular 2
In this lesson, we’ll work through a complete example of how to code forms in Angular 2. We’ll create a form component that can display and edit information. Follow along and I’ll show you how to use the essential features of two-way data binding and input validation.
This Angular 2 template snippet creates an input field. The value of the input field is two-way connected with the
model.name field defined in the corresponding .component.ts file. The name of the input field is
"name". And finally, a reference is created to the field as
nameField, which can be referred to elsewhere in the template. The
nameField ref is used below the input field, to show or hide a
<div>, depending on the state of the input field.
<div> <h3>Name</h3> <input type="text" id="name" required [(ngModel)]="model.name" name="name" #nameField="ngModel"> <div [hidden]="nameField.valid || nameField.pristine"> Name is required </div> </div>