I am trying to add a class that will change its appearance (e.g. burger to x), to a menu trigger DOM element that has its own method to show an overlay menu, but I can't figure out how to do it.
Here is what I have so far - this is calling an external method for the menu itself:
import { Component, ElementRef, ViewChild, Renderer, AfterViewInit } from '@angular/core';
import { LayoutService } from 'app/core/services/layout.service';
@Component({
moduleId: module.id,
selector: 'header-main',
templateUrl: 'header-main.component.html',
})
export class HeaderMainComponent {
@ViewChild('nav-trigger') el: ElementRef;
constructor(private layoutService: LayoutService) { }
menuToggle() {
this.layoutService.mainMenuToggle();
this.el.nativeElement.classList.add('opened');
}
}
I am new to Angular 2. How is this supposed to work-out? Should I use the Renderer
, why I should use the Renderer
? And etc. questions
EDIT: The issue with the absolute click event (selecting the child, not the parent) is that we have to use a reference tag paired with the @ViewChild
decorator as so:
@ViewChild('navTrigger') navTrigger: ElementRef;
which relates to the #navTrigger
reference in the HTML template.
Therefore:
export class HeaderMainComponent {
logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts
@ViewChild('navTrigger') navTrigger: ElementRef;
constructor(private layoutService: LayoutService, private renderer: Renderer) { }
menuToggle(event: any) {
this.layoutService.mainMenuToggle();
this.renderer.setElementClass(this.navTrigger.nativeElement, 'opened', true);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…