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 Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.