Search code examples
angularangular2-routingrouterlink

Angular - Get Event on Parent Component using routerLink


I'm emitting an event from child component to parent component like this

Child Component

export class ItemComponent {

  @Output() id = new EventEmitter()

  deleteProduct(id) {
    this.id.emit(id)
  }

}

Child Component tag

<app-product-item (id)="getId($event)"></app-product-item>

Receive the event on my Parent Component

getId(id){
  console.log(id)
}

This is working fine.

Now I need to have the same behavior but whit a component that I access by routerLink and not whit a tag like <app-product-item (id)="getId($event)"></app-product-item> this does not exist because I'm accessing it by routerLink.

Routing config:

const routes: Routes = [
    { path: '', component: WinesComponent },
    { path: 'app-wines', component: WinesComponent },
    { path: 'app-about', component: AboutComponent },
    { path: 'app-wine-detail/:id', component: WineDetailComponent },
    { path: 'app-wine-add', component: WineAddComponent }
];

Solution

  • You can use BehaviorSubject from RxJs to emit/trigger event from one component from another component.

    assume we have a service file named common.service.ts

    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs';
    
    @Injectable({
      providedIn: 'root',
    })
    export class CommonService {
      constructor() {}
      // Observable User details
      private id = new BehaviorSubject<any>('');
      id$ = this.id.asObservable();
    
      // user details
      deleteProduct(id: any) {
        this.id.next(id);
      }
    }
    

    child.component.ts

    import { CommonService } from '../common.service';
    
    constructor(private commonService: CommonService) {
      this.commonService.deleteProduct(100); //example id = 100
    }
    

    parent.component.ts

    import { CommonService } from '../common.service';
    
    constructor(private commonService: CommonService) {
      this.commonService.id$.subscribe((id) => {
        // here id = 100 received
        console.log(id); // from child component
      });
    }