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

时间:2016-12-25 16:06:24

标签: css angular encapsulation

我正在制作一个简单的hello world应用程序(目前从角度1迁移)我使用angular-cli生成我的组件,它创建了一个样式表并通过styleUrls将其链接到我的组件中。除非我这样做,否则我的风格都不会按照我认为的方式应用。#34; 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 :(得分:1)

你需要使用这个css:

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

答案 1 :(得分:0)

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

我假设你在app-header的某个地方使用header.component.html 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() { }
}

答案 2 :(得分:0)

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