As I embark on creating my inaugural Angular2 application, I find myself delving into the realm of angular cli for guidance. One particular feature I am attempting to implement is a show/hide toggle functionality for a hamburger menu catered towards smaller screens. The structure of my application appears as follows:
|-- app
|-- src
|-- navigation
|-- navigation.component.ts
|-- navigation.service.ts
|-- navigation.template.html
|-- main.ts
|-- main.template.html
|-- system-config.ts
|-- index.html
My goal is to execute a simple action upon clicking a button in my navigation.template.html
:
<button type="button" class="navbar-toggle collapsed" (click)="toggleMenu()">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
This click event triggers a method in my navigation.component.ts
file:
togMenu: boolean = false;
//... more code then,
toggleMenu(): void {
this.togMenu = !this.togMenu;
this.navigationService.toggleMenuEvent.emit(this.togMenu);
}
The method relies on a service within the same directory with the following implementation:
import {Injectable, EventEmitter} from '@angular/core';
@Injectable()
export class NavigationService {
toggleMenuEvent: EventEmitter<boolean> = new EventEmitter();
}
Although seemingly straightforward, upon attempting to capture the emitted value in the main.template.html
, I encounter a roadblock. By listening for the Event Emitter in the main.ts
file using the constructor:
showMenu: boolean = false;
constructor(private navigationService: NavigationService) {
navigationService.toggleMenuEvent.subscribe(
(val) => {
this.showMenu = val;
});
}
I realize that the event fails to propagate to the parent Component. Despite thorough debugging efforts - and the absence of any console errors - the showMenu
variable retains a false state. While transferring the relevant code snippet to the child component yields success in event emission detection, it does not successfully transmit the event upward to the parent (main
) component. Puzzled by this discrepancy, I remain uncertain about the root cause of this issue. It is worth noting that my experimentation is based on the Angular2 release candidate.
Suggestions from various sources prompt the consideration of utilizing Observables instead of Event Emitters. Regrettably, my lack of knowledge in Observables has led me to pursue the existing approach described here.
Please bear in mind that I have omitted extraneous code to streamline this inquiry.