angular-单击时将类添加到DOM元素 [英] angular - Adding a class to a DOM element when clicked

查看:238
本文介绍了angular-单击时将类添加到DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个将更改其外观的类(例如,将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中,类setElementClassaddClass代替.根据 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆