【问题标题】:CSS is not working in my angular componentCSS 在我的角度组件中不起作用
【发布时间】:2018-05-30 17:40:09
【问题描述】:

我正在尝试制作一个简单的 Angular4 网络应用程序,该应用程序将根据评分显示 X 或 O。我在我的网络应用程序中看不到 X 或 O。

我的 rating.component.ts 文件中的 CSS 类不起作用。我的项目正在编译,因为我可以将文本添加到我的评分组件模板中,它会显示在网页上,但我看不到应该呈现的 CSS。

我的应用组件:

import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
    template: `
        <rating></rating>
     `,
  styleUrls: ['./app.component.css']
})

export class AppComponent {
}

我的评分组件:

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

@Component({ 
    selector: 'rating', 
    template: `                   
        <i class="star" 
        [class.star-empty-icon]="rating < 1" 
        [class.star-full-icon]="rating >= 1" 
        (click)="onClick(1)">
        </i>
        <i class="star" 
        [class.star-empty-icon]="rating < 2" 
        [class.star-full-icon]="rating >= 2" 
        (click)="onClick(2)">
        </i>
    `
})
export class RatingComponent{ 
    rating = 0; 
    onClick(ratingValue){ 
        this.rating = ratingValue; 
    } 
}

我的 CSS:

.star.star-full-icon{
    content:'X';
}
.star.star-empty-icon{
    content:'O';
}

【问题讨论】:

  • 是的!在 CSS 中添加 :before 有效。 @serpent5

标签: css angular


【解决方案1】:

如果你不想弄乱 ViewEncapsulation 并且仍然有样式隔离,you can define the style within your global css file(例如styles.scss)通过在组件选择器前加前缀:

rating .star.star-full-icon{
    content:'X';
}

这是在 Angular 10 Web 应用程序中测试的。

【讨论】:

    【解决方案2】:

    更新

    ::slotted 现在被所有新浏览器支持并且可以与 `ViewEncapsulation.ShadowDom 一起使用

    https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted

    原创

    您需要添加 CSS(['./app.component.css'])RatingComponent,否则样式封装会阻止应用 CSS。

    或者,您可以使用::ng-deep

    ::ng-deep .star.star-full-icon{
        content:'X';
    }
    ::ng-deep .star.star-empty-icon{
        content:'O';
    }
    

    ViewEncapsulation.NoneRatingComponent

    但我建议坚持第一个选项。

    另见https://blog.thoughtram.io/angular/2015/06/29/shadow

    【讨论】:

    • 这不起作用。还是空白页。不过感谢您提供的信息。
    • ng-deep 即将被弃用:)
    • 不,不是。当所有浏览器都与Native 兼容并且不再需要Emulated 时,它将被移除。
    • 如果类按预期设置,您是否检查过 DOM?
    • 示例应该以 ::ng-deep 开头(而不是 :ng-deep)。双冒号是必须的。
    【解决方案3】:

    我相信您遇到的问题是因为您在父组件上声明了styleUrls,并且由于封装,它们在子组件中不可用。您必须将其移至评级组件。

    如果您想将其保持在当前级别,则需要在评级组件上使视图封装为无。

    selector: 'rating',
    encapsulation: ViewEncapsulation.None
    

    我相信您也滥用了 content css 属性。您需要使用::before::after 伪元素

    .star.star-full-icon::after{
        content:'X';
    }
    .star.star-empty-icon::after{
        content:'O';
    }
    

    【讨论】:

    • 这不起作用。还是空白页。不过感谢您提供的信息。
    • 但是类是在元素上设置的吗?
    • 正确。我看到了这个:
    • 您确实将 styleUrls 移至评级组件,对吧?
    • 是的,它在 rating.component.ts 中。
    猜你喜欢
    • 2020-06-16
    • 2022-01-06
    • 1970-01-01
    • 2022-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多