Coding With Fun
Home Docker Django Node.js Articles FAQ

Angular 2 data binding


May 08, 2021 Angular2


Table of contents


Describe

Data binding is the synchronization of data between model and view components. /b10> To display component properties, you can place their names in a view template, enclosed in double braces. /b11> Bidirectional data binding uses instruction ngModel to merge properties and event bindings in a single symbol.

Example

The following example describes the use of data binding in Angle 2:

<!DOCTYPE html>
<html>
   <head>
      <title>Data Binding</title>
      <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/es6-shim.min.js"></script>
      <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system-polyfills.js"></script>
      <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2-polyfills.js"></script>
      <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system.js"></script>
      <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/typescript.js"></script>
      <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/Rx.js"></script>
      <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2.dev.js"></script>
      <script>
         System.config({
           transpiler: 'typescript',
           typescriptOptions: { emitDecoratorMetadata: true },
           packages: {'app': {defaultExtension: 'ts'}}
         });
         System.import('/angular2/src/app/data_binding_main')
               .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 file .html typescript version. /b10> SystemJS converts TypeScript to JavaScript before running the application using the transpiler option.

  • If you don't translate to JavaScript before you run your application, you may see compiler warnings and errors hidden in your browser.

  • When the emitDecorator Metadata option is set, TypeScript generates metadata for each class of code. /b10> If you do not specify this option, a large amount of unused metadata is generated, which affects the file size and the application runtime.

  • Angular 2 contains packages from the app folder, Chinese will have a .ts extension.

  • Next, it loads the main component file from the app folder. /b10> If the primary component file is not found, it displays an error in the console.

  • When Angula called the boot function in main.ts, it reads the Company metadata, finds the "app" selector, locates an element label named app, and loads the application between them.

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

data_binding_main.ts
import {bootstrap} from 'angular2/platform/browser';           //importing bootstrap function
import {AppComponent} from "./data_binding_app.component";     //importing component function

bootstrap(AppComponent);

Now we'll create a component in the TypeScript (.ts) file, as follows:

data_binding_app.component.ts
import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: `
           <ul>
              <li
              *ngFor="#Item of Items"
              (click)="onItemClicked(Item)">
                  {{ Item.name }}
              </li>
           </ul>
           <input type="text" [(ngModel)]="clickedItem.name">
   `
})
export class AppComponent {
     public Items = [
                     {name: "Butter"},
                     {name: "Milk"},
                     {name: "Yogurt"},
                     {name: "Cheese"},
                  ];
     public clickedItem = {name: ""};
     onItemClicked(Item) {
        this.clickedItem = Item;
     }
}
  • @Component is an decorator that uses configuration objects to create components and their views.

  • The selector creates an instance of the component where the tags in the parent HTML are found.

  • Next up is the sngFor instruction to create a view export that we bound in the template. /b10> It is an abbreviation for using the Angular 2 template syntax and template tags.

  • You can refer to the local variable Item in the template and get an index of the array. /b10> When you click on the project value, the onItemClicked() event is activated and Angular 2 binds the name of the model to the local variable of the template.

  • When the user clicks the item name from the list, the model name clickedItem is bound to the name and the item name is displayed in the text box.

Output

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

  • Save the HTML code above as an index .html file, as we created in the Development Environment section, and use the application folder above that contains the .ts file.

  • Open the terminal window and enter the following command:

    npm start
  • Later, the browser tab should open and display the output, as shown below.

Alternatively, you can run this file in other ways:

  • Save the HTML code above as a file in the server root angular2_data_binding.html folder.

  • Open this HTML file as http://localhost/angular2_data_binding.html and display the output as shown below.

This example appears in the project name when you click the item name from the list.