Jeremy Foster
Jeremy Foster

Reputation: 4763

How to show parent component properties in a child component [angular2]

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

Answers (3)

Thierry Templier
Thierry Templier

Reputation: 202196

I would see several ways to do that:

Upvotes: 0

Chandermani
Chandermani

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

Sasxa
Sasxa

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

Related Questions