Hugo Seleiro
Hugo Seleiro

Reputation: 2657

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 }
];

Upvotes: 0

Views: 828

Answers (2)

Raghul Selvam
Raghul Selvam

Reputation: 315

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
  });
}

Upvotes: 1

kszalai
kszalai

Reputation: 63

You could pass the data through a service to the component you need to access it from.

https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

Upvotes: 1

Related Questions