代码之家  ›  专栏  ›  技术社区  ›  Zeus

如何使用Angular 6中的模拟封装更改子组件样式?

  •  0
  • Zeus  · 技术社区  · 7 年前

    这是样品 demo

    app.component.ts

    <hello name="{{ name }}"></hello>
    <p>
      Start editing to see some magic happen :)
    </p>
    

    您好,component.ts

    import { Component, Input } from '@angular/core';
    
    @Component({
     selector: 'hello',
      template: `<h1 class='test'>Hello {{name}}!</h1>`,
      styles: [`.test { font-family: Lato;color:red; }`]
    })
    export class HelloComponent  {
      @Input() name: string;
    }
    

    :host ::ng-deep .test{
      color:green;
    }
    
    p {
      font-family: Lato;
    }
    

    我可以在chrome工具栏中看到,它试图覆盖样式,但子组件仍然显示颜色:红色。

    enter image description here

    2 回复  |  直到 7 年前
        1
  •  2
  •   penleychan    7 年前

    在你的CSS中有一点几乎没有。

    :host ::ng-deep hello .test{
      color:green;
    }
    

    哪里 hello

    https://stackblitz.com/edit/angular-74ajje

        2
  •  1
  •   joh04667    7 年前

    这个 :host 伪选择器以主机为目标 您的组件(例如。 <app-hello>

    ::ng-deep 有点不同。当Angular编译组件样式时,此选择器将使样式作为其自身封装上下文的一部分向下渗透到所有子组件。

    你在说什么 :host ::ng-deep .test { [_nghost-c1] 以及作为具有class=“test”的宿主元素的子元素的所有元素。

    .test { ,封装在此组件中,表示“针对此组件中的每个元素(编译为 [_ngcontent-c1] )使用class=“test”。

    h1

    推荐文章