Saturday, June 11, 2016

Angular JS - Better form binding

We have "Add Contact" component working. But we are in search of a better way to do form bindings. The way we did in our previous exercise does work, but it is tough to keep up with a growing form. We want a better way and there is

new-contact.component.ts

/**
 * Created by krishnansriramrama on 5/28/16.
 */
import {Component, OnInit} from 'angular2/core';
import {ContactsService} from "./ContactsService";
import {Contact} from "./Contact";

@Component({
    selector: 'new-contact',
    template: `
<h2>Add a new contact</h2> <div> <form (submit)="saveContact()"> <div> <label>First Name</label> <input type="text" id="firstName" [(ngModel)]="formContact.firstName"> </div> <div> <label>Last Name</label> <input type="text" id="lastName" [(ngModel)]="formContact.lastName"> </div> <div> <label>EMail ID</label> <input type="text" id="emailId" [(ngModel)]="formContact.emailId"> </div> <div> <label>Phone Number</label> <input type="text" id="phoneNumber" [(ngModel)]="formContact.phoneNumber"> </div><br> <div id="formbox"> <button type="submit">Save contact</button> <button type="reset">Cancel</button> </div> </form> </div> `, styles:[ ` label { display: inline-block; width: 140px; text-align: right; margin: 10px; }​ input { margin-top: 5px; margin-bottom: 5px; display:inline-block; *display: inline; /* for IE7*/ zoom:1; /* for IE7*/ vertical-align:middle; margin-left:20px } #formbox { width:400px; margin:auto 0; text-align: center; } button { width: 125px; text-align: center; } ` ] }) export class NewContactComponent implements OnInit { formContact: Contact = new Contact(); postResponse = null; postError = null; constructor(private _contactsService:ContactsService) {} saveContact() { this._contactsService.saveContact(this.formContact).subscribe( response => this.postResponse = response, error => this.postError = error ); } checkAndPrintError() { console.log("POST complete"); if(this.postError != null) { console.log(this.postError); } else { console.dir(this.postResponse); } } }

What we have achieved here is pretty simple two-way binding. You may want to also read on observer pattern in Angular2.

No comments:

Post a Comment