【问题标题】:Is it possible to use [ngClass] on an app component where the class is inside the component for Angular 6?是否可以在类位于 Angular 6 组件内部的应用程序组件上使用 [ngClass]?
【发布时间】:2018-07-17 16:40:46
【问题描述】:

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

app.component.html

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

我的页脚.css

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

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

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

谢谢!

【问题讨论】:

    标签: javascript angular angular6


    【解决方案1】:

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

    我的页脚.css

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

    app.component.html

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

    【讨论】:

      【解决方案2】:

      将组件样式保留在组件内部。你想改变你的方法:

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

      在这种情况下,它只会在您的条件为真时构造页脚。

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

      家长:

      someCondition: boolean;
      

      HTML:

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


      孩子:

      @Input() condition: boolean;
      


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

      【讨论】:

      • 对不起,我应该写的问题更类似于我所希望的。使用ngIf 显示很容易,但是如果我想根据条件更改组件的background-color 怎么办?我想在app.component 中执行此操作,因为正在那里进行检查,所以我希望该值会传播到组件并根据需要应用样式。我更新了我的问题,使其更符合我的要求。对此感到抱歉。
      • 我已经编辑了我的答案,所以现在你有另一种方法。祝你好运 ! @J-man
      【解决方案3】:

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

      你可以这样做:

      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;
        }
      }
      

      【讨论】:

        【解决方案4】:

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

        父级 (HTML):

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

        儿童 (TS):

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

        子 (HTML)

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

        【讨论】:

        • 这里的class1是一个变量
        猜你喜欢
        • 2019-01-03
        • 1970-01-01
        • 1970-01-01
        • 2019-05-01
        • 1970-01-01
        • 2019-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多