Angular 1 and Angular 2 Integration

Angular 2 Component Outputs [@Output Property]

@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 4 vs. Angular 2

If you want to bind an event on an element, you can use the new Angular2 events i.e.

@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>

Stayed Informed – 69 Best Angular 2 Interview Q/A

I hope you are enjoying with this post! Please share with you friends. Thank you so much!
ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.