我目前正在学习Angular 2.我知道如何使用Angular Renderer设置ElementStyle,但现在我想使用Renderer方法:

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

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

推荐答案

最初的OP询问如何使用渲染器.为了完整起见,我加入了@HostBinding.

使用@HostBinding

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

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

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

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

  constructor() {
  }
}

使用@HostBinding with multiple classes

为了让多个类更易于使用,您可以使用ES6 getter并在返回之前将这些类连接在一起:

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.如果有一组要应用于元素的动态类,则Render2非常有用.

Example:

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');
  }
}

Angular相关问答推荐

如何将CDkDropList与Angular FormArray和FormGroup一起使用?

Angular 形式验证:在空和不匹配的密码上显示错误

在forkjoin中使用NGXS状态数据

无法执行CanDeactivateFn Karma Test Angular 16

Ionic 5角形共享两个模块之间的组件

当嵌套在异步容器中时,S会阻止具有动态值的ionic 段工作吗?

bootstrap 可折叠菜单在单击时未展开.Angular 应用程序

Angular 17-getEnvironment InjectorProviders出现异常

如何在 Angular 中每 x 秒从 REST api 加载数据并更新 UI 而不会闪烁?

NX MFE Angular 模块联合无法访问远程微前端

VSCode 调试器空白页面并在使用 VS Code 1.76.1 和 Chrome 111 启动时加载

导入 AngularFirestoreModule 时出现问题:此类型参数可能需要 `extends firebase.firestore.DocumentData` 约束.

Chart.js 如何编辑标题标签 colored颜色

如何从 RxJS 重试中排除某些 url

如何设置Angular 4背景图片?

如何在angular material中使用输入类型文件

EmptyError: no elements in sequence

Angular:ViewChild 上未定义 nativeElement

Angular 2 Material - 如何居中进度微调器

如何从materialAngular使用分页器?