As I delve into teaching myself Angular2, I've encountered a practical issue that would have been easy to solve with AngularJS. Currently, I'm scouring examples to find a solution with Angular2. Within my top-level component named App
, there's a property applying a css class. Here is the HTML template for the component, where I intend to apply the css class using ngClass
. The showMenu
value is simply a boolean.
<div class="navigation" role="navigation">
<ul>
<li><a [routerLink]="'Home'">Home</a></li>
<li><a [routerLink]="'Mail'">Mail</a></li>
<li><a [routerLink]="'Friends'">Friends</a></li>
<li><a [routerLink]="'Games'">Games</a></li>
</ul>
</div>
<!-- below is where I wish to toggle the class -->
<div class="site-wrap" [ngClass]="{'slide-right': showMenu}">
<div class="container-fluid">
<div class="row nav">
<top-navigation></top-navigation>
</div>
</div>
<div class="container-fluid content-gradient">
<div class="row">
<div class="col-md-10">
<router-outlet></router-outlet>
</div>
<div class="col-md-2">
<contacts-list></contacts-list>
</div>
</div>
</div>
<div class="container-fluid footer">
<footer-navigation></footer-navigation>
</div>
</div>
Presented below is the basic Component Code for App:
export class App {
showMenu: boolean = false;
constructor() {
}
// Need a way to listen for the toggle
toggleMenu():void {
this.showMenu = !this.showMenu;
}
}
The child component with the selector top-navigation
has a method on a button that toggles the value of showMenu
in the parent/top-level component. Here are some snippets of the code so far:
export class TopNavigation {
constructor() {
// Operations happening here
}
toggleMenu():void {
// Aim to toggle the parent property through some form of $emit
}
}
Displayed below is a snippet of the template HTML for the Component:
<div class="col-xs-2 col-sm-1 hidden-md hidden-lg hamburger-menu">
<button class="btn btn-default" (click)="toggleMenu()">☰</button>
</div>
In the context of AngularJS, I typically used $scope.$emit
on the toggleMenu
function and had a corresponding $scope.$on
in the parent to capture the event. Currently exploring EventEmitters
in Angular2, but if anyone can provide a quick explanation or example, it would be greatly appreciated as this seems like a common task for Angular developers.