繁体   English   中英

是否可以在类位于Angular 6组件内部的应用程序组件上使用[ngClass]?

[英]Is it possible to use [ngClass] on an app component where the class is inside the component for Angular 6?

我有一个angular 6应用程序,我正在尝试将另一个CSS类应用于app.component.html文件中的一个我的应用程序组件。 基本上,我想根据条件更改应用程序页脚的颜色,而其他所有情况都不显示页脚。 因此,我的代码如下所示:

app.component.html

<router-outlet></router-outlet>
<my-footer [ngClass]="{ 'my-class' : true }"></my-footer>

我-footer.css

:host {
    background-color: black;
    color: white;
}

.my-class {
    background-color: red;
}

是否可以以这种方式使用[ngClass] ,而该类存在于我对其施加条件的组件中? 我发现如果将.my-class放在app.component.css文件中,那么它将按预期工作。 但是,我想将样式保留在它们所属的组件中。

谢谢!

将组件样式保留在组件内。 您想将方法更改为:

<my-footer *ngIf="ifMyCondition === true"></my-footer>

在这种情况下,仅当您的条件为true时,它才会构造页脚。

UPDATE--
正如您在评论中提到的那样,我仍然建议您处理组件内部的组件需求,而不要依赖外包(在您的情况下是父级?)来更改组件属性。 因此,我建议您在孩子中使用Input()来从父母那里获得状况的状态,然后根据需要进行处理。

家长:

someCondition: boolean;

HTML:

<my-footer [condition]="someCondition"></my-footer>


儿童:

@Input() condition: boolean;


现在,每次父母中的条件发生变化时,与孩子的绑定都会不断更新他,因此您可以根据父母中的绑定条件来管理子组件中的所需内容。

使用选择器:host.my-class似乎可以正常工作,如本stackblitz所示。

我-footer.css

:host {
    background-color: black;
    color: white;
}

:host.my-class {
    background-color: red;
}

app.component.html

<my-footer [ngClass]="{ 'my-class' : condition }"></my-footer>

您可以根据条件申请课程。

您可以执行以下操作:

app.component.html

<router-outlet></router-outlet>
<my-footer [ngClass]="{ 'my-class' : displayFooterBg() }"></my-footer>

app.component.ts

displayFooterBg = () => {
  if (this.condition === true) {
    return true;
  } else {
    return false;
  }
}

您可以将类作为子组件的输入。

父母(HTML):

<my-footer [classValue]="class1"></my-footer>

儿童(TS):

@Input() public classValue = 'default-class';

儿童(HTML)

<div ngClass = {{classValue }}></div>

暂无
暂无

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

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