如何使用 HostBinding 添加未知的 class?
How can I add an unknown class with HostBinding?
我想使用 HostBinding
装饰器来添加一个 class,它不能像 @HostBinding('class.myClass')
.
那样被硬编码
我知道可以将它绑定到整个 class
属性,例如 @HostBinding('class')
,但这显然会重置所有直接添加到我的主机元素的 classes使用的地方。
那么是否可以使用HostBinding
,但只添加一个class并在html中保留所有先前添加的class?
目前我得到了更丑陋的解决方案:
@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);
}
}
用 @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>
我想使用 HostBinding
装饰器来添加一个 class,它不能像 @HostBinding('class.myClass')
.
我知道可以将它绑定到整个 class
属性,例如 @HostBinding('class')
,但这显然会重置所有直接添加到我的主机元素的 classes使用的地方。
那么是否可以使用HostBinding
,但只添加一个class并在html中保留所有先前添加的class?
目前我得到了更丑陋的解决方案:
@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);
}
}
用 @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>