I want a given component to be able to reference its parent component. Actually, I have some application state (an option selected by the user) that I want to be able to use from anywhere within the application. Which is the best pattern: a) reference the property on my component's parent component or b) somehow make the application state available globally to all components. And how would this look?
Asked
Active
Viewed 417 times
3 Answers
2
If something needs to shared across the application, it better be encapsulated into a service and registered during the bootstrapping process.
export class AppService {
private _state:any;
set(state){
this.state=state;
}
get() {
return this._state
}
}
Register it during bootstrap
bootstrap(App,[AppService]);
And inject it in both Parent and Child component. Parent calls set
and child calls get
In case if the state is just local to the component then you can use simple property binding input as @Sasxa pointed out.

Chandermani
- 42,589
- 12
- 85
- 88
-
I ended up using this strategy and it's working great. – Jeremy Foster Feb 20 '16 at 17:48
1
You can pass value from parent to child via property binding/input properties, like so:
<parent>
<child [state]="value">
class Parent {
public value = 123;
}
class Child {
@Input() state;
ngOnInit() {
console.log(state);
}
}
And for b), I would highly recommend @ngrx/store
.

Sasxa
- 40,334
- 16
- 88
- 102
0
I would see several ways to do that:
- Create an
@Input
in the child component to provide the value to display. See this link for more details: `Error: Output is not defined` when passing value outside a directive to parent directive - Inject the parent component instance into the child one. This way the child component will have access to the parent properties. See this answer for more details: Angular2 Exception: No provider for Service
- Use a shared service with dedicated properties to make communicate parent and child components. See this link for more details: Delegation: EventEmitter or Observable in Angular2

Community
- 1
- 1

Thierry Templier
- 198,364
- 44
- 396
- 360