简体   繁体   English

如何在组件内部设置模板样式

[英]How to style template inside the component

So, I want to pass a template to the component and render this template inside with style applied from this component, not from the calling component. 因此,我想将模板传递给组件,并使用从该组件而不是从调用组件应用的样式来呈现此模板。 Is it any way to do this without setting ViewEncapsulation.None ? 有没有设置ViewEncapsulation.None吗?

I made a small stackblitz for that. 为此,我做了一个小型的堆叠闪电战。 I want param button also rendered green. 我希望param button也呈绿色。

https://stackblitz.com/edit/angular-zrpufe?file=src%2Fapp%2Fhello.component.ts https://stackblitz.com/edit/angular-zrpufe?file=src%2Fapp%2Fhello.component.ts

Just try this one 试试这个

  styles: [`
   ::ng-deep button {
       background: green;
    }
  `]

Use the ::ng-deep shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. 使用:: ng-deep-sharing-piercing后代组合器将样式强制向下通过子组件树进入所有子组件视图。 The ::ng-deep combinator works to any depth of nested components, and it applies to both the view children and content children of the component. :: ng-deep组合器适用于嵌套组件的任何深度,并且适用于该组件的视图子级和内容子级。

EDIT: This deep selector has been deprecated for a long time and CSS Work Group has not agreed on an alternative yet. 编辑:此深层选择器已被弃用很长时间,CSS工作组尚未就替代方案达成共识。 Untill there is a replacement I favor to use deep, because, while alternative solutions like wrapping the element with a div and styling globally is good to go, it has problems too, the biggest issue with it, it doesnt work inter-modules in angular. 直到有我喜欢深度使用的替代方法为止,因为虽然其他解决方案(例如,用div包裹元素和全局样式化)是可行的,但它也有问题,最大的问题是,它不能按角度在模块间工作。 It is up to you to decide. 由您决定。

I do not recommend using ::ng-deep at all. 我根本不建议使用::ng-deep It is deprecated and in time will be removed for good. 它已被弃用,并且将被永久删除。

Check this answer . 检查此答案

I changed your code and added a container div for your HelloComponent. 我更改了代码,并为HelloComponent添加了一个容器div With a class on that div you can control the styles inside your component. 通过该div上的类,您可以控制组件内部的样式。 Any style that you write like that in your main style.css file won't need ::ng-deep or ViewEncapsulation.None . 您在主style.css文件中编写的任何样式都不需要::ng-deepViewEncapsulation.None

 // styles.scss .hello-container button { background: green; } 
 // hello.component.ts -> template <div class="hello-container"> ... </div> 

OR 要么

even simpler: 更简单:

You do not need the container div , just add this in your style.css 您不需要容器div ,只需在您的style.css中添加它即可

hello button {
      background: green;
    }

'hello' is the selector for your component and it will apply that style to EVERY button in your component. “ hello”是组件的选择器,它将样式应用于组件中的每个按钮。

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

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