【问题标题】:Writing css for Angular 2 View encapsulation via styleUrl通过 styleUrl 为 Angular 2 View 封装编写 css
【发布时间】:2016-12-25 16:06:23
【问题描述】:

我正在制作一个简单的 hello world 应用程序(目前从 angular 1 迁移)我使用 angular-cli 生成我的组件,它创建了一个样式表并通过 styleUrls 将其链接到我的组件中。除非我执行“viewEncapsulation.none”,否则我的所有样式都不会按照我认为的方式应用。有什么我想念的吗?或者有没有更好的方法为此写出 css?

如果我使用默认封装(ViewEncapsulation.Emulated 甚至原生),我的样式根本不会显示。

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

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  encapsulation: ViewEncapsulation.None,
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

constructor() { }

ngOnInit() {
}
}

我的 CSS 如下所示:

.app-header{
    display: block;
    opacity:0.2;
}

【问题讨论】:

  • 我编辑了我的回复。你解决了这个问题吗?

标签: css angular encapsulation


【解决方案1】:

你需要使用这个css:

:host() {
    display: block;
    opacity:0.2;
}

【讨论】:

    【解决方案2】:

    不要操作组件标签,这个标签范围属于使用它的父组件。仅操作 html 模板组件中的标签。

    【讨论】:

      【解决方案3】:

      我认为您需要在组件声明中设置module:module.id 以在正确的位置搜索文件。您是否已验证 CSS 是否已在非工作案例中加载?

      我假设您在header.component.html 的某个地方使用app-header css?试试下面的代码。

      import { Component, OnInit } from '@angular/core';
      import { ViewEncapsulation } from '@angular/core';  
      
      @Component({
        module: module.id,
        selector: 'app-header',
        templateUrl: './header.component.html',
        styleUrls: ['./header.component.css']
      })
      export class HeaderComponent implements OnInit {
      
        constructor() { }
      
        ngOnInit() { }
      }
      

      【讨论】:

      • 谢谢你把这个放在我的装饰器里吗? moduleId: 'app-header',
      • angular-cli 不使用模块 ID。
      • 您能否将您的组件HTML文件的内容也放入问题中,以便我给出更详细和完整的示例。
      猜你喜欢
      • 2016-11-10
      • 1970-01-01
      • 2018-10-08
      • 2020-01-14
      • 2019-08-03
      • 2019-10-29
      • 2017-01-22
      • 1970-01-01
      • 2017-04-26
      相关资源
      最近更新 更多