Как я могу добавить неизвестный класс с HostBinding?
Я хочу использовать 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);
}
}
1 ответ
Переопределение родного class=""
атрибут с @Input() class: string;
выглядит многообещающе Я не проверил это очень тщательно, но, похоже, это работает до сих пор.
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>