首页 > 解决方案 > 有条件地将类应用于组件主机

问题描述

仅当某些情况属实时,我才尝试将类应用于组件标记。

如何将此主机变成条件主机,以便在需要时应用所需的类?

@Component({
  selector: 'k-sidebar',
  host: {
   class: '{{isChanged}}'
 },
 templateUrl: './ng-k-side-bar.component.html',
 encapsulation: ViewEncapsulation.None

})

标签: angularangular-components

解决方案


您可以有条件地设置宿主元素类@HostBinding

condition: boolean = true;

@HostBinding("class") private get hostClass(): string {
  return this.condition ? "redBorder" : "";
}

或对于特定的类名(例如redBorder):

@HostBinding("class.redBorder") private get hasRedBorder(): boolean {
  return this.condition;
}

请参阅这两个演示:stackblitz 1stackblitz 2


推荐阅读