【问题标题】:Adding class to Angular2 component HTML markup does not apply the styles向 Angular2 组件 HTML 标记添加类不会应用样式
【发布时间】:2017-08-10 09:54:37
【问题描述】:

在 Angular2 中,当我像这样在自定义 Angular2 组件上添加类标签时:

<my-component class="someClass"></my-component>

...样式不会应用于 HTML。在 Chrome 开发人员工具中,当我选择 my-component 元素时,样式检查器显示正在应用样式,但从视觉上看,它们没有。这是正常的吗?我该如何解决?

【问题讨论】:

  • 请贴出组件装饰器部分

标签: html css angular


【解决方案1】:

Angular 2 使用 Shadow DOM,它是 Web Components 标准的一部分,支持 DOM 树和样式封装。 Angular View Encapsulation

因此,如果您想在 my-component 中设置样式,则应在 my-component 类中编写您的类。

import { Component, OnInit } from '@angular/core';

@Component({
    teamplte: '<h1 class="myClass">i am my-component</h1>',
    styles: [`
      .myClass {
         someProp: value;
      }
    `]
})

export class ConatinerComponent implements OnInit {
    constructor() { }

    ngOnInit() { }
}

但是如果你想在外部设置样式,你必须在容器组件中编写你的样式和类!

import { Component, OnInit } from '@angular/core';

@Component({
    teamplte: '<my-component class="myClass"></my-component>',
    styles: [`
      .myClass {
         someProp: value;
      }
    `]
})

export class MyComponentComponent implements OnInit {
    constructor() { }

    ngOnInit() { }
}

【讨论】:

    【解决方案2】:

    如果你想传递 className 之类的任何东西,请使用绑定:

    @Component({
     selector: 'my-component',
     template: template,
     styleUrls: ['app/components/nav-bar/nav-bar.style.css'], // or you can add explicit style,
    bindings:{
      className: '<'
    }  
    })
    

    HTML

     <my-component class-name="someClass"></my-component>
    

    希望这会对你有所帮助。

    【讨论】:

    • Angular2 在我这样做时抛出一个错误:Argument of type '{ selector: string;模板网址:字符串; styleUrls: 字符串[];绑定:{类名:字符串; }; }' 不可分配给“组件”类型的参数。对象字面量只能指定已知属性,而“组件”类型中不存在“绑定”。
    【解决方案3】:

    您为什么使用这种方法?您只需在my-component 中添加一些样式即可。

    CSS

    my-component {
       background: black;
       text-align: center;
     }
    

    当然,在你的组件中添加html代码

    【讨论】:

    • 实际上,这对我在 Chrome(或任何其他浏览器)上不起作用。我遇到的问题与我最初的问题相同:开发人员工具告诉我样式存在,但从视觉上看,它不是。
    猜你喜欢
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 2017-08-04
    • 2019-04-30
    • 1970-01-01
    • 2017-11-11
    相关资源
    最近更新 更多