I\'m currently teaching myself Angular2 and I have a practical problem that would be easy to rectify in AngularJS but currently I\'m looking through examples to find a solut
I could leverage a shared service that define an EventEmitter
property. Your App
component will subscribe on it to be notified when the corresponding event is trigger by the TopNavigation
component.
Shared service
@Injectable()
export class MenuService {
showMenuEvent: EventEmitter = new EventEmitter();
}
Don't forget to define the corresponding provider in the boostrap function to be able to share the same instance of the service for the whole application: `bootstrap(App, [ MenuService ]);
App
component
@Component({ ... })
export class App {
showMenu: boolean = false;
constructor(menuService: MenuService) {
menuService.showMenuEvent.subscribe(
(showMenu) => {
this.showMenu = !this.showMenu;
}
);
}
}
TopNavigation
component:
export class TopNavigation {
constructor(private menuService: MenuService) {
// Things happening here
}
toggleMenu():void {
this.showMenu = this.showMenu;
this.menuService.showMenuEvent.emit(this.showMenu);
}
}
See this question for more details:
You can use two-way binding.
<top-navigation [(toggleMenu)]="showMenu"></top-navigation>
maybe one-way would do as well, I don't know your exact requirements
<top-navigation (toggleMenuChange)="showMenu=$event"></top-navigation>
export class TopNavigation {
@Output() toggleMenuChange: EventEmitter = new EventEmitter();
// for two-way binding
@Input() toggleMenu:boolean = false;
constructor() {
// Things happening here
}
toggleMenu():void {
this.toggleMenu = !this.toggleMenu;
this.toggleMenu.emit(this.toggleMenu);
}
}