zoukankan      html  css  js  c++  java
  • [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 {
    }
  • 相关阅读:
    grunt 使用比较
    一些技术要点
    git 使用笔记
    oo的一些概念
    借用构造函数继承非原型
    bower解决js的依赖管理
    需要了解的一些东西
    一些常用的代码
    js模式(一):单例模式
    写给自己的计划
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7599728.html
Copyright © 2011-2022 走看看