angular-单击时将类添加到DOM元素 [英] angular - Adding a class to a DOM element when clicked
问题描述
我试图将一个将更改其外观的类(例如,将burger更改为x )添加到菜单触发DOM元素,该元素具有自己的方法来显示覆盖菜单,但是我可以无法弄清楚该怎么做.
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');
}
}
我是Angular 2的新手,应该如何解决?我应该使用Renderer
吗,为什么要使用Renderer
?等问题
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
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;
,与HTML模板中的#navTrigger
引用相关.
@ViewChild('navTrigger') navTrigger: ElementRef;
which relates to the #navTrigger
reference in the HTML template.
因此:
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);
}
}
推荐答案
自从泰勒(Tyler)回答以来,情况有所改变. Renderer
被折旧,并由Renderer2
代替.在Renderer 2
中,类setElementClass
被addClass
代替.根据 docs 的说明,addClass
的新功能签名是
Since Tyler's answer, things have changed a bit. Renderer
is depreciated and replaced by Renderer2
. In Renderer 2
, the class setElementClass
is replaced by addClass
. And the new function signature for addClass
, according to the docs is
addClass(el: any, name: string): void
因此更新后的menuToggle
函数应显示为
So the updated menuToggle
function should read
menuToggle(event:any) {
this.renderer.addClass(event.target,"opened");
}
这篇关于angular-单击时将类添加到DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!