Reputation: 35
I just want to do some experiment. So when I click a button of a A component, some function of a B component should invoke. But I don't know how to do that if these components are not parent child to each other. Can you please help me
Upvotes: 1
Views: 110
Reputation: 5040
When there is no child-parent relationship between components
You should create a service having a Subject
and inject this service in both of these components.
some.service.ts
@Injectable()
export class SomeService {
public testSubject = new Subject<string>();
}
comp-a.component.ts
export class CompAComponent {
constructor(private someService: SomeService) {
}
btnClickHandler() {
this.someService.testSubject.next('clicked');
}
}
comp-b.component.ts
export class CompBComponent {
constructor(private someService: SomeService) {
this.someService.testSubject.subscribe(next => { this.someFunction(data);});
}
someFunction(msg) {
console.log(msg);
}
}
Upvotes: 2