How to Emit Data from Routing Component in Angular 4

Posted By : Vishal Kumar | 30-Oct-2017

This is the technique to pass data from one component to another component. Means it is the easiest way to do component interation. It is the comonly used feature in angular and also a most important feature.

You can also use @Output and @Input for component intraction but these annotations are only worked for if your components are in the relation of child and parent. If your component has no relation like child and parent or in the same hierarchy the you have to use this method for component intration. 

Here i am using 2 components HomeComponent and AppComponent for passing data from home component to app component.

Step 1: First of all you have to create a service for emitting data from one component to another.

event.emmiter.service.ts

import {Injectable, EventEmitter} from '@angular/core';

@Injectable()
export class EventEmiterService {

  dataStr = new EventEmitter();

  constructor() { }

  sendMessage(data: string) {
    this.dataStr.emit(data);
  }
}

Step 2: Now import this service in your app module providers[] array of NgModule() like below

 @NgModule({
  declarations: [...],
  imports: [..],
  providers: [EventEmiterService],
  bootstrap: [AppComponent]
})

Step 3: Now import emitter service in your home.component.ts and add below code in the same file

sub: Subscription;

constructor(private _eventEmiter: EventEmiterService, private router: Router) {


  ngOnInit() {
   this.sub = this.router
      .data
      .subscribe(v => {
          console.log(v);
          this._eventEmitter.sendMessage(v)
       });

  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

Step 4: Now add this following code to your app.component.ts, don't forget to import emitter service.

constructor(private _eventEmiter: EventEmiterService) {
  }

  setDataStr() {
    this._eventEmiter.dataStr.subscribe(data => console.log(data))
  }

Conclusion: In this code i am sending a message or data from home component to app component at the time of initialization of home comonent. You can perform this action on a button click or according to you requirment.

Thanks,

About Author

Author Image
Vishal Kumar

Vishal Kumar is Master in Computers Application. He has good technical skills in Java and always motivated to learn new things.

Request for Proposal

Name is required

Comment is required

Sending message..