• [Angular] Use :host-context and the ::ng-deep selector to apply context-based styling


    If you want to style host component. You can use ':host-context'.

    // host
    
    @Component({
      selector: 'my-app',
      template: `
        <div class="styled-component">
          <hostcontext-styling></hostcontext-styling>
        </div>
      `,
    })

    In the host component, we have 'styled-component' class, we want to apply some css to it from the child component:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'hostcontext-styling',
      template: `
        <div>
          I'm a div that wants to be styled
        </div>
      `,
      styles: [
        `
          /* apply a border if any of our ancestors has .styled-component applied */
          :host-context(.styled-component) {
            border: 1px solid gray;
            display:block;
          }
        `
      ]
    })
    export class HostContextStylingComponent {
    }

    Now if we want to style its child component, we can use '::ng-deep':

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'hostcontext-styling',
      template: `
        <div>
          I'm a div that wants to be styled
        </div>
        <child-component></child-component>
      `,
      styles: [
        `
          /* apply a border if any of our ancestors has .styled-component applied */
          :host-context(.styled-component) {
            border: 1px solid gray;
            display:block;
          }
          
          :host ::ng-deep p {
            background-color: yellow;
          }
        `
      ]
    })
    export class HostContextStylingComponent {
    }
  • 相关阅读:
    react-native 调用原生方法
    react-native 生命周期
    查看ubuntu系统信息
    Python之DataFrame将列作为索引
    Python之读取文本文件
    Python 之 直接赋值、Deepcopy、Copy区别
    Python之time与datetime模块
    Python之连接MySQL数据库,执行建表语句
    Python之读取csv文件
    MySQL之count() 函数
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7599728.html
Copyright © 2020-2023  润新知