Reputation: 4763
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?
Upvotes: 1
Views: 424
Reputation: 202196
I would see several ways to do that:
@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 directiveUpvotes: 0
Reputation: 42669
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.
Upvotes: 2
Reputation: 41274
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
.
Upvotes: 1