Web
Analytics
Angular 4 custom event | event emiiter service | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Event Emitter and data Passing from Child Component to the parent component.

Step1 : Create Child Component(mycomponent);

cd src/app

 ng g c mycomponent –flat

Step 2:

Write Following code into mycomponent.ts

import { Component, OnInit , EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-mycomponent',
  
  template: `
    <button (click)="clickchild()">Click me!</button>
  `
})
export class MycomponentComponent {


  @Output() clicked = new EventEmitter<string>();
  clickchild() {
    this.clicked.emit('This is Child Component Code!');
  }


}





Step 3: Pass reference of newly created component(mycomponent) into app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';

import { MycomponentComponent } from './mycomponent.component';

@NgModule({
  declarations: [
    AppComponent,
    MycomponentComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

Step 4: Update app.component

import { Component , EventEmitter, Output } from '@angular/core';
import { MycomponentComponent } from './mycomponent.component';
@Component({
  selector: 'app-root',
template: `
<h2>sdsd</h2>

<app-mycomponent (clicked)="onClicked($event)"></app-mycomponent>
<p>{{childdata}}</p>
`

})
export class AppComponent {

    childdata= '';

    onClicked(value: string) {
        this.childdata = value;
    }

}


run code

ng serve –open