Skip to content

Instantly share code, notes, and snippets.

@2n2n
Created August 4, 2017 14:11
Show Gist options
  • Save 2n2n/9c7d11e2b4905dd8431f7f6a9cfac977 to your computer and use it in GitHub Desktop.
Save 2n2n/9c7d11e2b4905dd8431f7f6a9cfac977 to your computer and use it in GitHub Desktop.
Accessing the body tag of the angular app and toggling the class using angular 4 attribute directives
// since the <body> tag is inside the index.php and doesn't have any component.ts
<a alphaToggleNav class="sidebar-toggle" data-toggle="offcanvas" role="button">
// the alphaToggleNav directive will find the body tag, and will change the className depending on the state.
import { Directive, HostListener, Renderer2, ElementRef } from '@angular/core';
@Directive({
selector: '[alphaToggleNav]'
})
export class ToggleNavDirective {
// reference for the class names, key is the state, while value will be the el.className value.
private stateClassRef = {
normal: "skin-blue sidebar-mini",
collapsed: "skin-blue sidebar-mini sidebar-collapse"
}
private state = "normal"; // normal or collapsed
constructor(private el: ElementRef,private rd: Renderer2) { }
@HostListener('click') toggleState() {
this.state = this.state === "normal" ? "collapsed": "normal";
// do the toggling.
this.el.nativeElement.closest('body').className = this.stateClassRef[this.state];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment