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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM