是否可以在Angular 2中添加动态类来托管?

Ale*_*lia 15 angular2-template angular

我知道在Angular2中我可以通过这样做将一个类'red'添加到组件的selector元素:

@Component({
    selector: 'selector-el',
    host: {
        '[class.red]': 'true'
    },
    ...
})
Run Code Online (Sandbox Code Playgroud)

我想知道是否有办法向主机添加动态类,类似于你对NgClass的处理方式(我知道实际上不支持NgClass,我正在寻找可能的解决方案):

@Component({
    selector: 'selector-el',
    host: {
        '[NgClass]': 'colorClass'
    },
    ...
})
...
constructor(){
    this.colorClass = 'red';
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 19

Renderer小号setElementClass可以用来添加或删除的任意类.例如md-[color],color输入提供的位置

<some-cmp [color]="red">
Run Code Online (Sandbox Code Playgroud)
@Component({
// @Directive({
    selector: 'some-cmp',
    template: '...'
})
export class SomeComp {
    _color: string;

    @Input()
    set color(color: string) {
        this._color = color;
        this.renderer.setElementClass(this.elementRef.nativeElement, 'md-' + this._color, true);
    }

    get color(): string {
        return this._color;
    }

    constructor(private elementRef: ElementRef, private renderer: Renderer){}
} 
Run Code Online (Sandbox Code Playgroud)

另请参阅查找nativeElement.classList.add()替代方法


Thi*_*ier 14

你可以使用这样的东西:

@Directive({
  (...)
  host: {
    '[class.className]' : 'className', 
    '[class]' : 'classNames' 
  }
}
export class MyDirective {
  constructor() {
    this.className = true;
    this.classNames = 'class1 class2 class3';
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 你知道我们如何用新的建议来完成同样的事情吗? (3认同)

cra*_*bus 10

如果你喜欢它从外面可以结合改变@HostBinding@Input():

@Component({
    selector: 'my-component',
    template: ``
})
export class MyComponent {
    @HostBinding('class.your-class') @Input() isSelected: boolean;
}
Run Code Online (Sandbox Code Playgroud)


Ash*_*yan 8

我是这样做的。也许有人会派上用场

@HostBinding('class') get hostClasses() {
    return `some-class ${this.dynamicOne} ${this.disabled ? 'disabled' : ''}`;
}
Run Code Online (Sandbox Code Playgroud)

或 Simon_Weaver 的建议:(the return value can also be an array,谢谢!)

@HostBinding('class') get hostClasses() {
  const classList = ['some-class', this.dynamicOne];
  if( this.disabled) { classList.push('disabled'); }
  return classList;
}
Run Code Online (Sandbox Code Playgroud)


小智 7

import {Component, HostBinding} from 'angular2/core';

@Component({
  (...)
}

export class MyComponent {
  @HostBinding('class') colorClass = 'red';
}
Run Code Online (Sandbox Code Playgroud)


Tro*_*tyl 5

我最近制定了一个名为<ng-host>(受此问题启发)的指令,它将每个(非结构性)更改重定向到组件主机元素,用法:

@Component({
  template: `
    <ng-host [ngClass]="{foo: true, bar: false}"></ng-host>
    <p>Hello World!</p>
  `
})
class AppComponent { }
Run Code Online (Sandbox Code Playgroud)

在线演示可以在这里找到.

支持的用法在此定义.

我通过指令服务模式实现了这一点,即手动提供NgClass和使用它(在线演示)

由于DI机制,NgClass将获得ElementRef当前主机元素,Self()修饰符有助于保证它.因此不需要通过构造函数创建实例,因此仍然使用公共API.

结合类继承可能更简洁,可以在这里找到一个例子.