@Output decorator is used to binds a property of a component to send the data from child component to parent component and this is a one-way communication.
@Output decorates output properties and its binds a property of the type of angular EventEmitter.
Stayed Informed - Angular 2 @Inputs
Stayed Informed - Angular 2 @Inputs
@Component(...) class yourComponent { addUser(event) { } }
The method addUser() will be called when user clicked on button.
<button (click)="addUser()">Click</button>
<button (click)="addUser($event)"></button>
What happen if you want to create a custom event?
Now come to the outputs, if you want to create your custom event in Angular 2 that time we will use to new @Outputdecorator.
Examples,
import { Component} from 'angular2/core'; import { bootstrap} from 'angular2/platform/browser'; @Component({ selector: 'my-app', providers: [Service], template: '<div>Hello my name is {{name}}!</div>' }) class MyApp { constructor(service: Service) { this.name = service.getName(); setTimeout(() => this.name = 'Anil Singh,', 1000); } } class Service { getName() { return 'Hello'; } } bootstrap(App);
In the above example, we will need to import Output and Event-Emitter to create our new custom event.
import { Component , Output, EventEmitter} from 'angular2/core'; import { bootstrap} from 'angular2/platform/browser'; @Component({ selector: 'my-app', providers: [Service], template: '<div>Hello my name is {{name}}!</div>' }) class MyApp { constructor(service: Service) { this.userClicked.emit(this.user); this.name = service.getName(); setTimeout(() => this.name = 'Anil Singh,', 1000); } } class Service { getName() { return 'Hello'; } @Output() userClicked = new EventEmitter(); } bootstrap(App);
Now when we are using the components anywhere in our application, we can bind the custom event i.e.
<my-app (userClicked)="userClicked($event)"></my-app>
I
hope you are enjoying with this post! Please share with you friends. Thank you
so much!