【问题标题】:How can I add an unknown class with HostBinding?如何使用 HostBinding 添加未知类?
【发布时间】:2017-10-16 15:01:20
【问题描述】:

我想使用HostBinding 装饰器来添加一个类,它不能像@HostBinding('class.myClass') 那样硬编码。

我知道有可能将它绑定到整个 class 属性,例如 @HostBinding('class'),但这显然会重置所有直接添加到我使用它的宿主元素的类。

那么是否可以使用HostBinding,但只添加一个类并将之前添加的所有类保留在html中?

目前我得到了更丑的解决方案:

@Component({
    ...
})
class MyComponent implements OnInit {
    constructor(private hostElement: ElementRef,
                private renderer: Renderer2) { }

    ngOnInit() {
        const randomClass = `dynamic-${Math.floor(Math.random() * 10) + 1}`;
        this.renderer.addClass(this.hostElement.nativeElement, dynamicClass);
    }
}

【问题讨论】:

  • 这个@HostBinding('class.my-class') myclass= true;将 my-class 添加到 :host 元素
  • 是的,但正如我所说,我事先不知道我不想添加的类名。这就是我在示例中使用 Math.random 的原因。因此我不能使用硬编码class.my-class
  • 即使我不了解如何在不知道类的情况下设置元素的样式,我也能明白这一点 - 顺便说一句,我认为你的方式就是要走的路
  • 呵呵,是的,绝对有效。 :D 在现实世界的场景中,这个类实际上并不是完全动态的。有人正在为它编写样式,我们只是在给定的代码时间内不知道它。谢谢@Whisher
  • alligator.io/angular/using-renderer2 你也可以使用一个指令,你可以使用@Input 动态添加类

标签: angular angular2-hostbinding


【解决方案1】:

@Input() class: string; 覆盖本机class="" 属性看起来很有希望。我没有对此进行过彻底的测试,但到目前为止它似乎有效。

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

@Component({
    selector: 'gist-keeps-class',
    template: 'this component keeps class="class" attributes'
})
export class KeepsClass {

    @Input() booleanInput: boolean = false;
    @Input() stringInput: 'some-thing' | 'another-thing' | 'a-third-thing' = 'another-thing';

    @Input() class: string = ''; // override the standard class attr with a new one.
    @HostBinding('class')
    get hostClasses(): string {
        return [
            this.class, // include our new one 
            this.booleanInput ? 'has-boolean' : '',
            this.stringInput
        ].join(' ');
    }

}

带有这个的模板:

<gist-keeps-class 
  class="some classes" 
  [booleanInput]="true" 
  [stringInput]="some-thing"
></gist-keeps-class>

会输出这个:

  <gist-keeps-class class="some classes has-boolean some-thing" >
    this component keeps class="class" attributes
  </gist-keeps-class>

gist

【讨论】:

  • 完美答案一直在寻找
猜你喜欢
  • 1970-01-01
  • 2023-03-16
  • 2019-08-12
  • 1970-01-01
  • 1970-01-01
  • 2018-05-12
  • 2016-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多