Thursday, April 13, 2017

Data binding in Angular 2





Property binding


 html

<td><img [src]='product.imageUrl' 
                       [title]='product.productname'
                       [style.width.px]='imageWidth'
                       [style.margin.px]='imageMargin'>
                        </td>

Component
export class ProductListComponent{
     pageTitle:string='Product List';
     imageWidth:number=50;
     imageMargin:number=2;
     products:any[]=[
                    {
                      "productId": 1,
                      "productName": "Leaf Rake",
                      "productCode": "GDN-0011",
                      "releaseDate": "March 19, 2016",
                      "description": "Leaf rake with 48-inch wooden handle.",
                      "price": 19.95,
                      "starRating": 3.2,
                      "imageUrl": "http://openclipart.org/image/300px/
svg_to_png/26215/Anonymous_Leaf_Rake.png"
                  }
  • ngModel is basically 2 way
  • We need to include form module

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
//form module
import {FormsModule} from '@angular/forms'

import { AppComponent }  from './app.component';
import { UserComponent }  from './user.component';

@NgModule({
  imports:      [ BrowserModule,FormsModule ],
  declarations: [ AppComponent , UserComponent],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>

    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>

  <body>
    <my-app>Loading AppComponent content here ...</my-app>
  </body>
</html>

Event binding

Two way data binding
                                

ngModel directive a is part of FormsModule. We need to import it in AppModule






  • [ ] Square bracket is used to indicate property binding 
  • ( ) is used for event binding to send a notification to the user entered data back to the class property

No comments:

Post a Comment