简体   繁体   English

有条件地将 class 应用到组件主机

[英]Apply class conditionally to component host

I'm trying to apply a class to the component tag only if something is true.只有在某些情况下,我才尝试将 class 应用于组件标签。

How I could turn this host into a conditional host so that I will apply the desired class when needed?如何将此主机转换为条件主机,以便在需要时应用所需的 class?

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

})

You can set the host element class conditionally with @HostBinding :您可以使用 @HostBinding 有条件地设置主机元素@HostBinding

condition: boolean = true;

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

or for a specific class name (eg redBorder ):或者对于特定的 class 名称(例如redBorder ):

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

See these two demos: stackblitz 1 , stackblitz 2 .请参阅这两个演示: stackblitz 1stackblitz 2

if 'my-class' is a class name you setup it like this如果“我的班级”是 class 名称,您可以这样设置

@Component({
  selector: 'k-sidebar',
  host: {
   '[class.my-class]': 'isChanged'
 },
 templateUrl: './ng-k-side-bar.component.html',
 encapsulation: ViewEncapsulation.None
})
export class MyComponent {
  isChanged = true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM