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

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

Angular 2 Component Outputs [@Output Property] Angular 2 Component Outputs [@Output Property] Reviewed by Anil Singh on 5:01 AM Rating: (5)
www.code-sample.com/. Powered by Blogger.
^