Learning Angular2 From Zero (Entry03)

Learning Angular2 from Zero (03) Input & Output

Overview

This entry is mainly covered the Angular2 component Input and Output.

1. Component API

In real project, there are always need to pre-fill the component status from dabase, not just initialled to empty. And also need to pass the component data to trigger corresponding events (Output). So here we need to use Input and Output to generate the component API like below.

Alt text

2. Input

By using @Input annotation, we could realise the input properties binding.

1
2
3
4
5
6
7
8
import {Input} from 'angular2/core'; // Import 'Input'
@Component({
inputs: ['isFavorite:is-favorite'] // Another way to announce the input attributes
})
export class FavoriteComponent {
@Input('is-favorite') isFavorite = false; // Make isFavorite to input, alias as 'is-favorite'
}

And use the FavoriteComponent in host component.

1
<favorite [is-favorite]="post.isFavorite"></favorite> // post is the property of host component

3. Output

Similar to Input, by using @Output annotation, we could realise the output properties binding.

1
2
3
4
5
6
7
8
9
10
11
12
import {Output, EventEmitter} from 'angular2/core'; // Import 'Output' and 'EventEmitter'
@Component({
outputs: ['change:favoriteChange'] // Another way to announce the output attributes
})
export class FavoriteComponent {
@Output('favorite-change') change = new EventEmitter(); // Define 'change' event emitter
onClick() {
this.change.emit({ newValue: this.isFavorite }); // Publish 'change' event, the value is object
}
}

And use the FavoriteComponent in host component.

1
<favorite [is-favorite]="post.isFavorite"></favorite> // Once it clicked, trigger the change event. 'Post' is the property of host component

Reference

Github

All related code could find in Github