Wednesday, January 25, 2017

Improving angular 2 components


Strong typing 

  • Benefits of using typescript is its strong typing.Every property has a type, every method has a return type, every method parameter has a type
  • Strong typing helps minimize errors through better syntax checking
  • If we do not have a pre defined type then we can use any [ ]



Interface
  • To specify custom typing we can define an interface

       

Using an interface
                         


example for product interface
export interface Iproduct 
{
    productId:number;
    productName:string;
    productCode:number;
    releaseDate:string;
    price:number;
    description:string;
    starRating:number;
    imageUrl:string;

}
This interface has to be imported in the component as shown below
import {Component} from '@angular/core';
//Import interface
import {Iproduct} from './product';
//view for the component
@Component({
    selector:'pm-products',
    templateUrl:'app/products/product-list.component.html'

})

If the type does not match then we get an exception as shown below


No comments:

Post a Comment