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

如何在不使用ng deep的情况下从父级的SCS中设置子组件的样式?

  •  0
  • fermoga  · 技术社区  · 6 年前

    我一直在努力塑造一个 BoxedComponent 来自 HeaderComponent ::ng-deep ,但我找不到一个合适的方法。

    盒式组件 组件类只包含一个 ViewEncapsulation.None

    @Component({
      selector: 'labs-boxed',
      templateUrl: './boxed.component.html',
      styleUrls: ['./boxed.component.scss'],
      encapsulation: ViewEncapsulation.None,
    })
    export class BoxedComponent {}
    

    HTML

    <div class="boxed">
      <ng-content></ng-content>
    </div>
    

    我在它的SCSS文件中创建了两个类,可以在任何地方使用,但我意识到,由于同样的问题,我仍然无法对组件的响应进行样式化。

    .boxed {
      /* rules */
    }
    
    .tall .boxed {
      height: 500px;
      width: 360px;
    }
    
    .squared .boxed {
      height: 340px;
      width: 340px;
    }
    

    在里面 的HTML文件,我正在使用 labs-boxed 详情如下:

    <div id="who-we-are" class="d-flex justify-content-around">
      <labs-boxed [ngClass]="'tall'">
        <p>
        ...
      ...
    ...
    

    lab-boxed 的样式及其更改:

    .盒装的{…}

    等等,但没有成功。

    0 回复  |  直到 6 年前
        1
  •  0
  •   ysf Tathagat    6 年前

    BoxedComponent ViewEncapsulation.None 中定义的所有规则 boxed.component.scss HeaderComponent header.component.scss 与全球范围隔离,并变得特定于 头部组件 .事实上 ng-deep 通过使单一规则全球化而起作用。换句话说,它从孤立的范围中删除规则,并将其放入全局范围,这是在封装的样式文件中使单个规则全局化的唯一方法。不借助 深沉的 可以通过以下方式替代子零部件样式:;

    1. styles.scss 文件

      <labs-boxed class="custom-box-style">
      
      • 时尚。scss

      .custom-box-style .boxed {
        // new rules
      }
      
      • 在头球。组成部分html

      <labs-boxed #childEl class="squared">squared and red</labs-boxed>
      

      @ViewChild('childEl', {read: ElementRef, static: true}) childEl: ElementRef;
      
      ngAfterViewInit() {
        const box = this.childEl.nativeElement.getElementsByClassName("boxed");
        box[0].style.backgroundColor = "red"
      }
      

    Here is a demonstration 这两种方法都适用。