Angular 2 - Binding User Input



Description

The user can input the text or display the text value when you click on it by using the Angular event binding syntax.

Example

The below example describes use of binding to user input in the Angular 2:

<!DOCTYPE html>
<html>
  <head>
    <title>Angular 2 User Input</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/system-polyfills.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.6/angular2-polyfills.js"></script>
    <script src="https://code.angularjs.org/tools/system.js"></script>
    <script src="https://code.angularjs.org/tools/typescript.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.6/Rx.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.6/angular2.dev.js"></script>
    <script>
      System.config({
        transpiler: 'typescript',
        typescriptOptions: { emitDecoratorMetadata: true },
        packages: {'app': {defaultExtension: 'ts'}},
        map: { 'app': './angular2/src/app' }
      });
      System.import('app/user_input')
         .then(null, console.error.bind(console));
    </script>
  </head>
<body>
   <my-app>Loading...</my-app>
</body>
</html>

The above code includes the following configuration options:

  • You can configure the index.html file using typescript version. The SystemJS transpile the TypeScript to JavaScript before running the application by using the transpiler option.

  • If you do not transpile to JavaScript before running the application, you could see the compiler warnings and errors which are hidden in the browser.

  • The TypeScript generates metadata for each and every class of the code when the emitDecoratorMetadata option is set. If you don't specify this option, large amount of unused metadata will be generated which affects the file size and impact on the application runtime.

  • Angular 2 includes the packages form the app folder where files will have the .ts extension.

  • Next it will load the main component file from the app folder. If there is no main component file found, then it will display the error in the console.

  • When Angular calls the bootstrap function in main.ts, it reads the Component metadata, finds the 'app' selector, locates an element tag named app, and loads the application between those tags.

To run the code, you need the following TypeScript(.ts) files which you need to save under the app folder.

user_input.ts
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from "./app.component";

bootstrap(AppComponent);

Now we will create a component in TypeScript(.ts) file as shown below:

app.component.ts
import {Component} from 'angular2/core';
import {ItemListComponent} from './shopping-list.component';

@Component({
    selector: 'my-app',
    template: `
    <my-list></my-list>
    `,
    directives:[ItemListComponent]
})
export class AppComponent {}
  • The @Component is a decorator which uses configuration object to create the component.

  • The selector creates an instance of the component where it finds <my-app> tag in parent HTML.

  • The above app.component will import the ItemListComponent component and uses directives to include the component.

shopping-list.component.ts
import {Component} from "angular2/core";

@Component({
   selector:'my-list',
   template:`
      <ul>
         <li *ngFor="#listItem of listItems"
            (click)="onItemClicked(listItem)">{{listItem.name}}
         </li>
      </ul>
      <input type="text" [(ngModel)]="selectedItem.name">
      <button (click)="onDeleteItem()">Delete Item</button><br><br>
      <input type="text" #listItem>
      <button (click)="onAddItem(listItem)">Add Item</button>
   `
})

export class ItemListComponent{
   public listItems = [
      {name:"apple"},
      {name:"orange"},
      {name:"grapes"},
   ];
   public selectedItem = {name: ""};

   onItemClicked(listItem){
      this.selectedItem=listItem;
   }

   onAddItem(listItem){
      this.listItems.push({name:listItem.value});
   }

   onDeleteItem(){
      this.listItems.splice(this.listItems.indexOf(this.selectedItem),1);
   }
}
  • The template tells Angular how to display the component.

  • The *ngFor directive is used to loop the list of items from the array of listItems object.

  • The shopping-list.component component uses (click) for binding events.

  • To add an item, enter an item and click on Add Item button and to delete an item, click on the item and hit Delete Item button.

Output

Let's carry out the following steps to see how above code works:

  • Save above HTML code as index.html file as how we created in environment chapter and use the above app folder which contains .ts files.

  • Open the terminal window and enter the below command:

    npm start
  • After few moments, a browser tab should open and displays the output as shown below.

OR you can run this file in another way:

  • Save above HTML code as binding_user_input.html file in your server root folder.

  • Open this HTML file as http://localhost/binding_user_input.html and output as below gets displayed.

Click on any item and hit Delete Item to delete an item from the list and enter an item and click Add item to add an item.

Advertisements