代码之家  ›  专栏  ›  技术社区  ›  J-man

是否可以在应用程序组件上使用[NGClass],其中该类位于Angular6的组件内部?

  •  2
  • J-man  · 技术社区  · 7 年前

    我有一个角度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 文件,然后按预期工作。但是,我想将我的样式保存在它们所属的组件中。

    谢谢!

    4 回复  |  直到 7 年前
        1
  •  2
  •   ConnorsFan    7 年前

    使用选择器 :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
  •  2
  •   dAxx_    7 年前

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

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

    在这种情况下,只有条件为true时,它才会构造页脚。

    更新--
    正如您在评论中提到的,我仍然建议您在组件内部处理组件需求,而不是依赖于外包(在您的情况下是父级?)更改组件属性。所以我建议您在您的孩子中使用input()从您的父母那里获取您的状态,然后根据您的需要处理它。

    起源:

    someCondition: boolean;
    

    HTML格式:

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


    儿童:

    @Input() condition: boolean;
    


    现在,每次在父组件中更改条件时,与子组件的绑定都会不断更新,这样您就可以根据在父组件中绑定的条件管理子组件中所需的内容。

        3
  •  0
  •   Gregor Ojstersek    7 年前

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

    你可以这样做:

    app.component.html软件

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

    应用组件

    displayFooterBg = () => {
      if (this.condition === true) {
        return true;
      } else {
        return false;
      }
    }
    
        4
  •  0
  •   Flutterian    7 年前

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

    父(HTML):

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

    儿童(TS):

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

    子(HTML)

    <div ngClass = {{classValue }}></div>
    
    推荐文章