简体   繁体   English

将 CSS class 有条件地应用于 Angular 组件主机

[英]Apply CSS class conditionally to Angular component host

I have an angular component with boolean input parameters.我有一个带有 boolean 输入参数的 angular 组件。 Based on whether they are true or false, I want to add a CSS class to the host.根据它们是真是假,我想在主机上添加一个 CSS class 。 I know I can wrap my entire component in a div and use ngClass.我知道我可以将整个组件包装在一个 div 中并使用 ngClass。 But what if I don't want to add an extra div in my template?但是如果我不想在模板中添加额外的 div 怎么办? I just want the host to have those classes conditionally.我只是希望主人有条件地参加这些课程。 Is that possible?那可能吗? Say this is my component:说这是我的组件:

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

  constructor() {}
}

And this is what the template looks like:这就是模板的样子:

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

Now based on the value of isSomethingTrue and isThisAlsoTrue , I want to apply 2 different CSS classes or styles to the host (to add some margin-top).现在基于isSomethingTrueisThisAlsoTrue的值,我想将 2 个不同的 CSS 类或 styles 应用到主机(以添加一些边距顶部)。 How do I do that in the component?我如何在组件中做到这一点?

You can combine @HostBinding with an @Input property to apply a class conditionally to the component host, based on the property value.您可以将@HostBinding@Input属性结合起来,根据属性值有条件地将 class 应用到组件主机。 In the code below, classes class1 and class2 are applied to the host element depending on condition1 and condition2 respectively:在下面的代码中, class1class2分别根据condition1condition2应用于宿主元素:

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

The CSS styles can be defined as follows: CSS styles可以定义如下:

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

See this stackblitz for a demo.请参阅此 stackblitz以获取演示。


An alternative syntax is to set the host class bindings in the component metadata:另一种语法是在组件元数据中设置主机 class 绑定:

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

See this stackblitz for a demo.请参阅此 stackblitz以获取演示。

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

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