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.
Let’s start by looking into how browser components work, taking for example the browser native component
<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 input model into the component. Based on the model the view will be built accordingly.
- the component emits an output event named
selectionwhen 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:
- An internal Html/CSS tree that encapsulates how the component view is built
- a Controller class, which coordinates the interaction between the view and the input model