Reputation: 881
I am building an application in Angular2. I have two components, in which the second Component is loaded in the router-outlet of the first component.
Component 1
@Component({
selector: 'component1',
templateUrl: '
<div>
...
...
...
</div>
<router-outlet></router-outlet>
'
})
@RouteConfig([
{ path: '/component2', component: Component2, name: 'Component2', useAsDefault: true }])
export class Component1{
...
...
...
refresh(){
...
...
}
}
Now here is the Component2.
@Component({
selector: 'component2',
templateUrl: '
<div>
...
...
...
</div>
'
})
export class Component2{
...
...
...
thisFunctionShouldRefreshComponent1(){
//call Component1's refresh here
}
Can someone please tell me how to call the Component1's refresh method from Component2.
Upvotes: 0
Views: 87
Reputation: 3029
Like @Jiang YD said you need a service to communicate between the components. You have to be careful where you register the provider for the service. You can either do it at the root of the application or in the top level component. So that both of the components have the same instance of the service.
Here is a simple example using observable:
// The service
@Injectable()
export class SomeService {
refresh: Subject<boolean> = new BehaviorSubject<boolean>(false);
refresh() { this.refresh.next(true) }
}
// Component 1
@Component({
selector: 'c1',
// Register the provider here for example
providers: [SomeService]
...
})
export class Component1 {
constructor(
private _ss: SomeService
) {}
refresh() {
this._ss.refresh()
}
}
// Component 2
@Component({
selector: 'c2',
...
})
export class Component2 {
constructor(
private _ss: SomeService
) {
this._ss.refresh.subscribe(a => {
if (a) this.refresh();
})
}
refresh() {
...
}
}
Upvotes: 0