是否有可能增加一个动态类在2角到主机?

问题描述 投票:14回答:6

我知道,在我Angular2可以通过这样一类“红色”添加到组件的选择元素:

@Component({
    selector: 'selector-el',
    host: {
        '[class.red]': 'true'
    },
    ...
})

我不知道是否有一个动态类添加到主机,类似于您用NgClass做什么(我知道NgClass实际上不支持,我在寻找可能的解决方案)的方式:

@Component({
    selector: 'selector-el',
    host: {
        '[NgClass]': 'colorClass'
    },
    ...
})
...
constructor(){
    this.colorClass = 'red';
}
angular angular2-template
6个回答
14
投票

您可以使用类似的东西:

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

18
投票

所述Renderers setElementClass可用于添加或删除的任意类。对于其中md-[color]由输入提供示例color

<some-cmp [color]="red">
@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){}
} 

参见nativeElement.classList.add() alternative


10
投票

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

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

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

@Component({
  (...)
}

export class MyComponent {
  @HostBinding('class') colorClass = 'red';
}

5
投票

我最近做了一个指令称为<ng-host>(由this issue启发),它会重定向到组件主机元素,使用每个(非结构性)的变化:

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

在线演示可以发现here

支持的用途定义here

我已经通过指令来实现此作为服务模式,即手动提供NgClass和使用它像(online demo

由于DI机制,NgClass将获得当前主机元素的ElementRefSelf()修改有助于保证。因此,没有必要通过构造下的公共API使用创建一个实例,因此仍然。

这可能是在与类继承相结合更简洁,一个例子可以在here找到。


-1
投票

你可以做到以下几点:

import {Component} from "@angular/core"

@Component({
    selector: "[textbox]",
    host: {"class": "first-class secondClass ThirdClass AnYClaSs"},
    template: ...                                            
})
export class MyComponent { }

这是海事组织比采用可变的方式更直接。 应Angular2 RC5,RC6,RC7,最后的工作。在早期版本可以工作,但没有尝试它。

© www.soinside.com 2019 - 2024. All rights reserved.