Although the internals of Angular 2 are still changing, the beta version of the API was released in December 2015 and you can use it to build your apps. The components are better isolated in Angular 2 and if the notions of properties and events are well applied, its simpler to write truly reusable components that can be understood just by looking at an html template.

Browser components

Let’s start by looking into how browser components work, taking for example the browser native component select:

<select> 
    <option value="friend1">First friend</option>
    <option value="friend2">Second friend</option> 
    <option value="friend3">Third friend</option> 
</select>

This component like all browser components has some interesting properties:

  • we don’t need to be aware of it’s internal structure
  • we don’t need to look at other parts of the application to know what this component is doing and how it will behave

Angular 2 allows us to build UI components that are in every way similar to native browser components: encapsulated, reusable, and easy to reason about.

The Angular 2 components

This is an example of an Angular component: a friends list component, similar to the select native component but with support extra features:

<friendsListComponent [friends]="refData.FRIENDS"
   (selection)="onSelection($event)"
</friendsListComponent>

Here is what is going on here:

  • this component has an input property friends, via which we provide a list of friends. Properties are the input that a component receives, and we use them to pass in an inputmodel into the component. Based on the model the view will be built accordingly.
  • the component emits an output event named selection when a new friend is selected. Events are the output that a component produces. They report to the outside world a relevant change of the component internal state.

The internal structure of a component

Every component has two main internal parts:

  1. An internal Html/CSS tree that encapsulates how the component view is built
  2. Controller class, which coordinates the interaction between the view and the input model

Source of the article: www.alinmiu.com

Leave a Reply

Your email address will not be published. Required fields are marked *