【问题标题】:Styling child components template from parent component css angular从父组件css angular为子组件模板设置样式
【发布时间】:2020-09-08 18:33:45
【问题描述】:

如何使用 ::ng-deep 或其他东西从父组件中强制子组件的 CSS?

我有放置子组件的父组件:

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

不是在喜欢的组件里面有他跟随HTML:

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

现在我想将父级parent.component.cssfa-heart 类的颜色设置为白色。

我该怎么做?

【问题讨论】:

    标签: css angular parent-child ng-deep


    【解决方案1】:

    你可以这样做,在父组件的css中:

    parent.component.css:

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

    【讨论】:

      【解决方案2】:

      好吧,我会反对上面的人,建议你不要这样做。

      如果您将组件视为应用程序中的独立构建块,您会认为它是一个优势,它在您使用它的每个地方看起来都一样。使用 ::ng-deep 覆盖此行为会给您在较大的应用程序中带来麻烦。

      Angular 提倡使用@Inputs 作为向组件传递数据的接口。我的建议是使用@Input 来修改视图。或者,如果在更大的上下文中,您可以使用依赖注入来提供一个标记,为组件的所有子级指定主题。

      <app-likes theme="white"></app-likes>
      
      @Component({selector: 'app-likes'})
      class AppLikesComponent {
        @Input() theme: string;
      
        @HostBinging("class") get themeBinding() {
           return 'theme--' + this.theme;
        }
      }
      

      【讨论】:

      • 很多时候,当组件不是你自己的,或者是一个库时,你必须使用::ng-deep,在这种情况下。
      【解决方案3】:

      您可以在父组件中设置ViewEncapsulation 选项来移除影子DOM。这实质上允许子组件使用父组件中的选择器定义。

      试试下面的

      父组件

      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  {
      }
      

      父 CSS

      .fa-heart {
        color: white;
      }
      

      工作示例:Stackblitz

      【讨论】:

        猜你喜欢
        • 2016-07-31
        • 2021-12-27
        • 2021-09-27
        • 2021-09-19
        • 2019-05-05
        • 2018-09-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多