简体   繁体   English

在组件中应用CSS类,将影响整个CSS角度6

[英]Apply css class in component that will effect entire css angular 6

I have one component 我有一个组成部分

my.component.ts That has its own css like this my.component.ts像这样有自己的CSS

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'my-component',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.css']
})
export class NotificationComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
}

my.component.css my.component.css

.hello{
color:red;
}

The problem is that i want to use that class to be visible in entire project in html, i know i can put them globally, but i want to use it from component. 问题是我想使用该类在html的整个项目中可见,我知道可以将它们放到全局,但是我想从组件中使用它。

Now other components does not see that class :( 现在其他组件看不到该类了:(

Is there some kind of solution in Angular? Angular中有某种解决方案吗?

Please take a look at the documentation on View Encapsulation , especially at the "None" part: 查看有关View Encapsulation的文档,尤其是“无”部分:

None means that Angular does no view encapsulation. None表示Angular不进行视图封装。 Angular adds the CSS to the global styles. Angular将CSS添加到全局样式中。 The scoping rules, isolations, and protections discussed earlier don't apply. 先前讨论的范围规则,隔离和保护不适用。 This is essentially the same as pasting the component's styles into the HTML. 这本质上与将组件的样式粘贴到HTML中相同。

Apply it to the component decorators config object: 将其应用于组件装饰器配置对象:

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.scss'],
   encapsulation: ViewEncapsulation.None // <-- This
})

Add your css to app.component.css or style.css . 将CSS添加到app.component.cssstyle.css It will effect on whole application. 这将影响整个应用程序。

If you want your component css style to be accessible from other component the solution is view encapsulation . 如果您希望组件的css样式可从其他组件访问,则解决方案是视图封装

Example : 范例:

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'my-component',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class NotificationComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
}

Angular comes with view encapsulation built in, which enables us to use Shadow DOM or even emulate it, so what ViewEncapsulation.None will do is remove the shadow DOM, so there will be no style encapsulation Angular内置了视图封装功能,它使我们能够使用Shadow DOM甚至对其进行仿真,因此ViewEncapsulation所要做的就是删除Shadow DOM,因此不会进行样式封装

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM