How to reference HTML form elements in Angular 2

Angular is an amazing Javascript client-side framework for building modern applications. The Angular team at Google Inc. released Angular version 2 recently. Angular 2 contains a lot of new features that are not in Angular1.x. One of such feature is Template Reference Variables. According to the official website of Angular 2, “A template reference variable is a reference to a DOM (Document Object Model) element or directive within a template”. The idea is, variables can be reference anyway within the template. For example, a variable can be assigned to an input field and then reference within the template. Below are two examples on how to use template reference variables in Angular 2 applications. This article explore how to reference HTML elements like input field with Angular 2 template. If you have issue with setting up a development environment in Angular 2, please see one of my previous article on How to install Angular using CLI on Window 7 machine https://medium.com/@julyseven2002/how-to-install-angular-2-using-cli-on-windows-7-machine-e328199f4e5a#.uw1ibghl1 
or visit Angular 2 official website for details about development environment setup —https://angular.io/docs/ts/latest/guide/setup.html

Example 1

In this example you will assign variables firstname and lastname to two input fields respectively and then reference the variables within the template. See the code below:

file:app/app.component.ts
import { Component} from ‘@angular/core’;
@Component({
selector: ‘app-root’,
template:`<h1> Angular 2 Template Reference Variables</h1>
<section class=”half-page”>
<input class=”form-control” type=”text” #firstname
placeholder=”Enter firstname” required>
<input class=”form-control”type=”text” #lastname
placeholder=”Enter lastname” required>
<input class=”form-control” type=”submit”
(click)=’submitFunct(firstname.value, lastname.value);
firstname.value =””; lastname.value=””; ‘ >
</section>
         <section><p class=”well”>{{result}}</p></section>
`,
styles:[`
section{
margin:10px
}
`]
})
export class AppComponent {
result: string = “”;
  submitFunct(firstname,lastname): void {
if(firstname === “” || lastname === “”){
return
}else{
this.result = firstname + “ “ + lastname + “ “ +”
pressed submit button.”;
}
}
}
file: app/app.module.ts 
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent }  from './app.component';
@NgModule({
imports: [
BrowserModule,
FormsModule
],
declarations: [
AppComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }

In the above code, Component is imported from Angular 2 core . Next, Angular 2 component decorator is declared using @Component. There are three attributes in the @Component namely selector, template and styles.

selector -create and insert an instance of the component

template — is the HTML code that will be rendered

styles — is the CSS code for styling and presentation

In the template section, there are two input fields and one to hold firstname and the other to hold lastname. The variables #firstname and #lastname are assigned to input fields respectively. The submit button contain a method named submitFunc to submit the form controls.

The submit method is declared in AppComponent class to handle the form logic like consuming the input fields value and assigning them to result variable to be displayed within the template. If .. else logic was implemented to prevent the user from submitting an empty form. In the app.module file, FormsModule was imported for working with forms in Angular 2. Note, this is not the best approach of handling client-side validation in Angular 2. Angular 2 have built-in validations for form controls which you’ll see in the next example.

Example 1: Angular 2 Template Reference Variable

Live Implementation: https://plnkr.co/edit/S35J7dUUSxchQ6m8UeIz?p=preview

Example 2

In this example you will assign a variable named #valForm to ngForm directive.

file:app/app.component.ts
import { Component} from ‘@angular/core’;
@Component({
selector: ‘app-root’,
template:`<h2> Angular 2 Template Reference Variables with
ngForm</h2>
<section class=”half-page”>
<form #valForm=”ngForm”
(ngSubmit)=”submitFunc(valForm.value);“ >
<input class=”form-control” type=”text”
name=”firstname” ngModel
placeholder=”Enter firstname” required>
<input class=”form-control”type=”text”
name=”lastname” ngModel placeholder=”Enter lastname”
required>
<span class=”form-control”>
<input type=”radio” name=”gender” value=”Male”
ngModel required> Male
<input type=”radio” name=”gender” value=”Female”
ngModel required> Female
</span>
<input class=”form-control btn btn-primary”
type=”submit” [disabled]=”!valForm.form.valid”>
         </form>
</section>
<section class=”well” *ngIf=”hideLable”>
<h4>Firstname: {{result.firstname}} </h4>
<h4>Lastname: {{result.lastname}} </h4>
<h4>Gender: {{result.gender}} </h4>
</section>
`,
styles:[`
section{
margin:10px
}
.half-page {
width:300px;
margin:10px;
}
input[type=”text”]{
margin: 7px 0px;
}
input[type=”submit”]{
margin: 10px 0px;
}
`]
})
export class AppComponent {
result: string = “”;
hideLable : boolean = false;
submitFunc(value): void {
this.hideLable = true;
this.result = value;
console.log(value);
}
}

The form variable valFrom will act as a reference to all fields in the form. The form field must have a name attribute and Angular 2 ngModel directive. The class method submitFunc with argument valFrom.value is assigned to ngSubmit event. The ngSubmit fires an event and send the value of valForm.value to the submitFunc method in the class. The submitFunc receives the value. The value is an object of key — value pairs. The value is assign to result variable. The result variable renders the value in the view. The submit button contain ‘ [disabled]=”!valForm.form.valid” ’ validation logic. The valForm.form.valid is assigned to the disabled attribute which is a native HTML attribute. The ngForm directive provides build-in form.valid attribute for form validation. Note, ‘!‘ character check if the form is invalid then disable submit button else enable. The hideLable variable act as flag for *ngIf directive to hide or show the output view based on the state of the form. If form is submitted, show output view else hide. See the live implementation complete code.

Example: Angular 2 Template Reference Variable with ngForm

Live Implementation: https://plnkr.co/edit/K4owvKNjPObO8nIbk0dl?p=preview

In Angular 2, there are two ways to define form — Template Driven form and Form builder. Template driven form make use of ngForm directive which was used in the second example and FormModule. Template driven form is good for defining simple form behavior while Form builder allow us write code to solve complex form behavior using ReactiveFormModule and directives like FormBuilder, FormGroup and FormControl.

Please feel free to leave your thoughts and comments.

Happy learning!

Resources:

  1. Angular 2 Official website
    https://angular.io/docs/ts/latest/guide/template-syntax.html
  2. Rangle Angular 2 Training book
    https://angular-2-training-book.rangle.io/