使用指令向主机元素添加类

使用指令向主机元素添加类

本文介绍了使用指令向主机元素添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习Angular2.我了解了如何使用Angular Renderer设置ElementStyle,但是现在我想使用Renderer方法:

I am currently learning Angular 2. I understood how to use the Angular Renderer to set an ElementStyle, but now I would like to use the Renderer method:

setElementClass(renderElement: any, className: string, isAdd: boolean) : void

我的问题是如何将CSS类导入属性指令?我必须将我的CSS类转换为JSON吗?

My question is how can I import a CSS class to my attribute directive?Do I have to convert my CSS class to JSON?

推荐答案

原始OP正在询问如何使用Renderer.为了完整起见,我包括了@HostBinding.

Original OP was asking how to use Renderer. I've included the @HostBinding for completeness.

要向元素添加类,可以使用 @HostBinding

To add a class to an element you can use @HostBinding

import { Directive, HostBinding} from '@angular/core';

@Directive({
  selector: '[myDirective]',
})
export class MyDirective {

  @HostBinding('class')
  elementClass = 'custom-theme';

  constructor() {
  }
}

将@HostBinding与多个类一起使用

要使多个类更易于使用,可以使用ES6 getter并在返回它们之前将这些类连接在一起:

Using @HostBinding with multiple classes

To make multiple classes more comfortable to use, you can use the ES6 getter and join the classes together before returning them:

import { Directive, HostBinding} from '@angular/core';

@Directive({
  selector: '[myDirective]',
})
export class MyDirective {
  protected _elementClass: string[] = [];

  @Input('class')
  @HostBinding('class')
  get elementClass(): string {
      return this._elementClass.join(' ');
  }
  set(val: string) {
      this._elementClass = val.split(' ');
  }

  constructor() {
      this._elementClass.push('custom-theme');
      this._elementClass.push('another-class');
  }
}

使用渲染器

更底层的API是 Renderer2 .当您有一组要应用于元素的动态类时,Renderer2很有用.

Using Renderer

The more low level API is Renderer2. Renderer2 is useful when you have a dynamic set of classes you would like to apply to an element.

示例:

import { Directive, ElementRef, Renderer2 } from '@angular/core';

@Directive({
  selector: '[myDirective]',
})
export class MyDirective {

  constructor(private renderer: Renderer2, hostElement: ElementRef) {
    renderer.addClass(hostElement.nativeElement, 'custom-theme');
  }
}

这篇关于使用指令向主机元素添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:06