SoFunction
Updated on 2025-04-04

Angular parent-child component passes parameters through service

Today I encountered a problem when using ngx-translate to multi-language. I needed to click on the button on the login page and then call a method in the parent component.
At first I thought of @input and @output, but since it is not a simple parent-child component relationship, but a parent-child component relationship that contains routes, the @input method and @output method cannot be used.

Then search and found that there is an answer on *. It uses service to pass parameters. It is very useful, so I will share it with you.

First, create a service.


import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class SharedService {
 // Observable string sources
 private emitChangeSource = new Subject<any>();
 // Observable string streams
 changeEmitted$ = ();
 // Service message commands
 emitChange(change: any) {
 (change);
 }
}

Then inject this service into the module to which the parent component and child component belongs, remember to put it in providers.

Then introduce the service into the respective components of the parent and child components.

The child component passes parameters through the onClick method:


import { Component} from '@angular/core';
@Component({
 templateUrl: '',
 styleUrls: ['']
})
export class ChildComponent {
 constructor(
 private _sharedService: SharedService
 ) { }
onClick(){
 this._sharedService.emitChange('Data from child');
 }
}

The parent component receives parameters through the service:


import { Component} from '@angular/core';
@Component({
 templateUrl: '',
 styleUrls: ['']
})
export class ParentComponent {
 constructor(
 private _sharedService: SharedService
 ) {
 _sharedService.changeEmitted$.subscribe(
 text => {
 (text);
 });
 }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.