1

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?

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
Jeremy Foster
  • 4,673
  • 3
  • 30
  • 49

3 Answers3

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
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:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360