У меня есть этот код, который устанавливает класс на хосте:
@HostBinding('class.fixed') true;
Что я хотел бы сделать, так это сделать этот класс переменных, который я могу изменить. Как я могу это сделать?
У меня есть этот код, который устанавливает класс на хосте:
@HostBinding('class.fixed') true;
Что я хотел бы сделать, так это сделать этот класс переменных, который я могу изменить. Как я могу это сделать?
Это невозможно сделать переменной.
Вместо этого вы можете напрямую привязываться к свойству класса
@HostBinding('class') classes = 'class1 class2 class3';
Если у вас ограниченное количество классов, вы можете условно добавить каждый из них:
@HostBinding('class.c1') get c1 () { return this.useC1; }
@HostBinding('class.c2') get c2 () { return this.useC2; }
Обратите внимание, что .c1
и .c2
должны быть определены вне компонента.
Я должен противоречить другим ответам, нет причины, по которой связывание class.className
не должно работать. На самом деле, следующий формат работает правильно:
@HostBinding('class.className') variableName = true;
Если в вашем случае это не сработает, вам может понадобиться добавить область видимости в ваш класс CSS (вы можете увидеть обсуждение здесь).
Проблема в том, что HostBinding
видит только область хоста, поэтому, если вы определяете какой-либо стиль в метаданных вашего Component
вам нужно указать, что css принадлежит области хоста.
Вы можете легко указать область действия хоста, просто добавив :host
перед своим правилом CSS:
:host.className {
/* Your CSS here */
}
На месте
.className {
/* Your CSS here */
}
Если вы хотите, я создал рабочий Plunker, который вы можете увидеть, нажав здесь
Ответ Гюнтера не очень полезен, если некоторые имена классов уже привязаны к переменной.
Хороший способ объединить имена переменной класса строки с именами предопределенных классов булево стиля является использование имен классов пакета НМП.
Используйте его вместе с @HostBinding
и функцией setter, чтобы получить потрясающие результаты:
import * as classNames from 'classnames';
(...)
@HostBinding('class') get classes(): string {
return classNames(this.getDynamicClassName(), {
'is-open': this.isOpen,
'has-children': this.hasChildren
});
}
Вы можете создать отдельные команды с классом.
Например: у меня есть кнопка на моей странице и может содержать: default
, primary
, danger
и fluid
. Кнопка может иметь много разных состояний, но я покажу вам эти три состояния из-за огромного количества кода. Так что давайте начнем!
button.ts
//default button
@Directive({
selector: '[appButtonDefault]'
})
export class ButtonDefaultDirective {
// the name of the field is not important
// if you put this directive to element,
// this element will have the class called 'button--default'
@HostBinding("class.button--default")
private defaultClass: boolean = true;
}
//primary button
@Directive({
selector: '[appButtonPrimary]'
})
export class ButtonPrimaryDirective {
// the name of the field is not important
// if you put this directive to element,
// this element will have the class called 'button--primary'
@HostBinding("class.button--primary")
private primaryClass: boolean = true;
}
// danger button
@Directive({
selector: '[appButtonDanger]'
})
export class ButtonDangerDirective {
// the name of the field is not important
// if you put this directive to element,
// this element will have the class called 'button--primary'
@HostBinding("class.button--danger")
private dangerClass: boolean = true;
}
@Directive({
selector: '[appButtonFluid]'
})
export class ButtonFluidDirective {
// the name of the field is not important
// if you put this directive to element,
// this element will have the class called 'button--primary'
@HostBinding("class.button--fluid")
private fluidClass: boolean = true;
}
// you need to also create a component class,
// that import styles for this button
@Component({
//just put created selectors in your directives
selector: `[appButtonDefault], [appButtonPrimary],
[appButtonDanger], [appButtonFluid]`,
styleUrls: ['<-- enter link to your button styles -->'],
// it is required, because the content of <button> tag will disappear
template: "<ng-content></ng-content>"
})
export class ButtonComponent {}
// you don't have to do it, but I prefet to do it
@NgModule({
declarations: [
ButtonDefaultDirective,
ButtonPrimaryDirective,
ButtonDangerDirective,
ButtonFluidDirective,
ButtonComponent
],
exports: [
ButtonDefaultDirective,
ButtonPrimaryDirective,
ButtonDangerDirective,
ButtonFluidDirective,
ButtonComponent
]
})
export class ButtonModule {}
Не забудьте импортировать ButtonModule
в ваш файл app.module.ts
. Это очень важно.
app.component.html
<!-- This button will have the class 'button--default' -->
<button appButtonDefault>Default button</button>
<!-- But this button will have the class 'button--primary button--fluid' -->
<button appButtonPrimary appButtonFluid>Primary and fluid</button>
Надеюсь, это поможет.
@Input()
class = '';
@HostBinding('attr.class')
get btnClasses() {
return [
'btn',
this.someClassAsString,
this.enableLight ? 'btn-secondary-light' : '',
this.class,
].filter(Boolean).join(' ');
};
Вы можете захватить атрибут класса с помощью ввода и добавить то, что вам нужно, в привязке хоста.