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

田丰
2023-12-01

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

 

 类似资料: