首页 文章

为Angular 2编写css通过styleUrl查看封装

提问于
浏览
0

我正在创建一个简单的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;
}

3 回答

  • 0

    你需要使用这个css:

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

    不要操纵组件标记,此标记范围属于使用它的父组件 . 仅操作html模板组件中的标签 .

  • 0

    我认为你需要在angular的组件声明中设置 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() { }
    }
    

相关问题