【问题标题】:Apply CSS class conditionally to Angular component host有条件地将 CSS 类应用于 Angular 组件宿主
【发布时间】:2020-09-09 21:57:16
【问题描述】:

我有一个带有布尔输入参数的角度分量。根据它们是真是假,我想在主机上添加一个 CSS 类。我知道我可以将整个组件包装在一个 div 中并使用 ngClass。但是,如果我不想在模板中添加额外的 div 怎么办?我只是希望主人有条件地参加这些课程。那可能吗? 说这是我的组件:

 export class AssetDetailsComponent {
  @Input isSomethingTrue = true;
  @Input isThisAlsoTrue = true;

  constructor() {}
}

这就是模板的样子:

<h1> Page heading </h2>
<p> Details </p>

现在基于isSomethingTrueisThisAlsoTrue 的值,我想对主机应用2 个不同的CSS 类或样式(以添加一些margin-top)。如何在组件中做到这一点?

【问题讨论】:

  • ngClass 不需要在 div 标签中使用,您也可以在其他标签中使用 ngClass,例如您的情况 h1p。您也可以在这些标签中添加条件类。这样你就不需要任何额外的 div 来包装你的组件了。

标签: html css angular angular9


【解决方案1】:

您可以将@HostBinding@Input 属性结合起来,根据属性值有条件地将类应用于组件主机。在下面的代码中,class1class2 类分别根据 condition1condition2 应用于宿主元素:

@HostBinding("class.class1") @Input() condition1: boolean;
@HostBinding("class.class2") @Input() condition2: boolean;

CSS 样式可以定义如下:

:host.class1 {
  margin-top: 20px;
}
:host.class2 {
  margin-left: 10px;
}

请参阅this stackblitz 以获取演示。


另一种语法是在组件元数据中设置主机类绑定:

@Component({
  ...
  host: {
    "[class.class1]": "condition1",
    "[class.class2]": "condition2"
  }
})
export class ChildComponent {
  @Input() condition1: boolean;
  @Input() condition2: boolean;
}

请参阅this stackblitz 以获取演示。

【讨论】:

    猜你喜欢
    • 2018-04-30
    • 2019-03-22
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2016-10-19
    • 2021-10-01
    • 2020-09-02
    • 2020-08-02
    相关资源
    最近更新 更多