kfa
kfa

Reputation: 2146

Angular2 access variables from another component

Tried EventEmitter but no chance and so little documentation... Any help appreciated

I have a component called sidebar and another one called header, when you click on a button from the header, it should hide the sidebar... How would you achieve this in angular2 ?

thanks

Upvotes: 5

Views: 8235

Answers (1)

Maximilian Riegler
Maximilian Riegler

Reputation: 23506

This is pretty easy with a Service you share between your Components.

For instance a SidebarService:

@Injectable()
export class SidebarService {
  showSidebar: boolean = true;

  toggleSidebar() {
    this.showSidebar = !this.showSidebar;
  }
}

In your sidebar component just put a *ngIf with the showSidebar variable from the SidebarService. Also don't forget to add the service in the constructor.

@Component({
  selector: 'sidebar',
  template: `
      <div *ngIf="_sidebarService.showSidebar">This is the sidebar</div>
  `,
  directives: []
})
export class SidebarComponent {
  constructor(private _sidebarService: SidebarService) {

  }
}

In the component, where you want to handle the toggling of the sidebar also inject the SidebarService and add the click event with the service method.

@Component({
  selector: 'my-app',
  template: `
    <div>
      <button (click)="_sidebarService.toggleSidebar()">Toggle Sidebar</button>
      <sidebar></sidebar>
    </div>
  `,
  directives: [SidebarComponent]
})
export class App {
  constructor(private _sidebarService: SidebarService) {

  }
}

Don't forget to add the SidebarService to the providers in your bootstrap:

bootstrap(App, [SidebarService])

Plunker for example usage

Upvotes: 7

Related Questions