Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在angular元素中添加| remove css类?_Css_Angular - Fatal编程技术网

如何在angular元素中添加| remove css类?

如何在angular元素中添加| remove css类?,css,angular,Css,Angular,如何在angular元素中添加| remove css类 可以通过以下方式访问angular元素:this.elementRef.nativeElement(import{elementRef}from'@angular/core';)。 CSS类名是myclass constructor(public elementRef: ElementRef, private renderer: Renderer) { this.renderer.setElementClass(this.

如何在angular元素中添加| remove css类

可以通过以下方式访问angular元素:
this.elementRef.nativeElement
import{elementRef}from'@angular/core';
)。 CSS类名是
myclass

constructor(public elementRef: ElementRef, private renderer: Renderer)
{
        this.renderer.setElementClass(this.elementRef, 'class');
   // or 

            this.elementRef.nativeElement.classList.add('class');

}
  • 使用渲染器
  • 在本机元素上使用addClass

  • 您可以使用HostBinding来实现这一点,而无需使用渲染器或ElementRef。请参见此示例:

    import {Component, HostBinding} from "@angular/core";
    
    @Component({
       ...
    })
    export class myComponent {
        @HostBinding('class.myclass') visible: boolean = false;  // True when visible
    }
    

    有两种方法,一种是使用(ElementRef,Renderer)或使用Hostbinding 下面的示例演示如何根据单击事件添加和删除类 例如: 在variable的帮助下,我将一个open(而不是open,您甚至可以添加类名)类附加到HTML元素

    import { Directive, ElementRef, HostListener, HostBinding } from '@angular/core';
    @Directive({
      selector: "[appDropDown]",
    })
    export class DropdownDirective {
      @HostBinding('class.open') isOpen = false;
      constructor(private elRef: ElementRef) {
    
      }
    
      @HostListener('click') click(eventData: Event) {
        this.isOpen = !this.isOpen
      }
    }
    

    ElementRef例如: 下面的示例是使用渲染器时的Add方法

    import { Directive, ElementRef, HostListener, Renderer2, } from '@angular/core';
    
    
    @Directive({
      selector: "[appDropDown]",
    })
    export class DropdownDirective {
    
      constructor(private elRef: ElementRef, private renderer: Renderer2) {
    
      }
    
      @HostListener('click') click(eventData: Event) {
        this.renderer.setAttribute(this.elRef.nativeElement, 'class', 'open');
      }
    }
    
    如果您不使用渲染器,那么对于直接本机元素,您可以使用 this.elementRef.nativeElement.classList.add('class')

    注意:Renderer2适用于angula6版本`