简体   繁体   English

从父组件样式化子组件模板 css angular

[英]Styling child components template from parent component css angular

How to force CSS of child component from parent using::ng-deep or something?如何使用 :: ng-deep 或其他方式强制父组件的子组件为 CSS?

I have parent component where I put child component:我有放置子组件的父组件:

....parent.component...
<app-likes></app-likes>
.....parent.component......

Not inside that likes component there is he following HTML:不在那个喜欢的组件里面有他跟随 HTML:

<div class="mainDiv">
<div class="secondDiv"><i class="far fa-heart fa-3x"></i></div></div>

Now I want to set color of fa-heart class to white from parent parent.component.css .现在我想将父parent.component.cssfa-heart class 的颜色设置为白色。

How can I do that?我怎样才能做到这一点?

You can do this way, in the css of the parent component:可以这样做,在父组件的 css 中:

parent.component.css:父组件.css:

:host ::ng-deep .fa-heart {
  color: red;
}

or

:host ::ng-deep app-likes .fa-heart {
  color: red;
}

Well I will go against the folks above and suggest that you don't do this.好吧,我会 go 反对上面的人,并建议你不要这样做。

If you consider the component an isolated building block in your app, you would consider it an advantage, that it looks the same in every place you use it.如果您将组件视为应用程序中的独立构建块,您会认为它是一个优势,它在您使用它的每个地方看起来都一样。 Using::ng-deep to override this behaviour will cause you trouble in larger apps.使用 ::ng-deep 覆盖此行为会给您在大型应用程序中带来麻烦。

Angular promotes using @Inputs as the interface of passing data into the component. Angular 提倡使用@Inputs 作为将数据传递到组件的接口。 My suggestion is to use @Input to modify the view.我的建议是使用@Input 来修改视图。 Or, if in larger contexts you can use Dependency Injection to provide a token that specifies a theme for all children of a component.或者,如果在更大的上下文中,您可以使用依赖注入来提供一个标记,为组件的所有子项指定一个主题。

<app-likes theme="white"></app-likes>

@Component({selector: 'app-likes'})
class AppLikesComponent {
  @Input() theme: string;

  @HostBinging("class") get themeBinding() {
     return 'theme--' + this.theme;
  }
}

You could set the ViewEncapsulation option in the parent component to remove the shadow DOM.您可以在父组件中设置ViewEncapsulation选项以移除影子 DOM。 This essentially allows the child component to use the selector definitions from the parent component.这实质上允许子组件使用父组件的选择器定义。

Try the following尝试以下

Parent component父组件

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  encapsulation: ViewEncapsulation.None        // <-- no shadow DOM
})
export class AppComponent  {
}

Parent CSS家长 CSS

.fa-heart {
  color: white;
}

Working example: Stackblitz工作示例: Stackblitz

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

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