主机元素上的条件样式

Bry*_*t11 10 javascript angular

我有一个组件,它所做的只是渲染,它是这样的:

@Component({
     selector: 'my-comp',
     host: ???,
     template: `
         <ng-content></ng-content>
     `
})

 export default class MyComp {
   @Input() title: string;
   public isChanged: boolean;
 }
Run Code Online (Sandbox Code Playgroud)

该组件有一个isChanged属性,我想基于该isChanged属性在主机元素上应用样式.这甚至可能吗?

Thi*_*ier 12

你使用classstyle前缀.这是一个示例:

@Component({
  selector: 'my-comp',
  host: {
    '[class.className]': 'isChanged'
  },
  template: `
    <ng-content></ng-content>
  `
})
export default class MyComp {
  @Input() title: string;
  public isChanged: boolean;
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅Günter的答案:


Fra*_*rzi 8

使用@HostBinder的解决方案

可接受的解决方案是使用host元数据属性,这违反了 TSLint 的规则:

TSLint:使用 @HostBinding 或 @HostListener 而不是元host 数据属性(https://angular.io/styleguide#style-06-03

使用@HostBinding也可以实现同样的效果:

import { Component, HostBinding, Input } from '@angular/core';

@Component({
  selector: 'my-comp',
  template: `
    <ng-content></ng-content>
  `
})
export default class MyComp {
  @Input() title: string;
  public isChanged: boolean;
  @HostBinding('class.className') get className() { return this.isChanged; }
}
Run Code Online (Sandbox Code Playgroud)