11 October 2017

Angular 4, create your own custom binding

Sometimes, you want to create your own data binding, for example to use the same properties in different components to support modular programming. If you're unfamiliar with binding and component in Angular, please check my previous post about Angular. We use data binding to bind the html file to the business logic on the typescript file. But instead of using any existing properties of the html tag like [src]="" or [(ngModel)]= "" we can create our own.

  1. create a new sub-component. You can create it manually or using cli command: ng g c yourComponent --spec false. Now you can use the <app-yourComponent> tag in your app-component.html
  2. In the sub-component create an object you want to bind for e.g user
  3. Add @Input() decorator before the object declaration
  4. your HTML file will look like this when binding element object(in serverComponent) and serverElements array(in app.component)