5

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

kfa
  • 2,106
  • 4
  • 17
  • 22
  • you should create a service for the sidebar and bootstrap it, then inject it in any component and alter the properties through the service, [here is an almost similar problem](http://stackoverflow.com/questions/37069609/show-loading-screen-when-navigating-between-routes-in-angular-2/37070282#37070282) – Ankit Singh May 20 '16 at 11:26

1 Answers1

7

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

Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71
  • Thanks for the demo, it's works but I can't import the sidebar in the header. Both are imported by the AppComponent and I would like to keep things separated. Do you have any other solution ? – kfa May 19 '16 at 15:22
  • You can do it however you wish, it all revolves around the `SidebarService`, because that's how you save and change the state of the sidebar. The example was only to show how it works theoretically. – Maximilian Riegler May 19 '16 at 15:23