Search code examples
cssangularcss-selectorspseudo-class

How to apply pseudo classes like :hover to ng2 pseudo class :host


I know we can apply class styles to our host component in CSS like this:

:host(.active) {
   ...
}

Is there any way to apply pseudo classes like :hover in a similar way? :host(:hover) doesn't seem to work. Nor does :host:hover. I know I can apply classes for that using host listeners in JS but that's weird to do something like that in this case.

EDIT: I'm using Angular 2.2.0

EDIT2: My problem was that I haven't set :host to display: block so it was impossible to hover over it.


Solution

  • :host(:hover) { ... } should work but whether is working or not depends on @Component({ encapsulation: ViewEncapsulation.??? }).

    You have three options for ViewEncapsulation:

    • ViewEncapsulation.None - your component styles will be merged into global styles
    • ViewEncapsulation.Emulated - styles are renamed and unique attributes are added to elements in order to prevent global styles clashes. This emulates the shadow DOM.
    • ViewEncapsulation.Native - uses the shadow DOM. This needs to be supported by the browser.

    Note that :host(:hover) is correct and should work with all cases. :host:hover will work with None and Emulated but is not a correct way to write it for Native. Therefore, in order to be compliant try using :host(:hover).

    Therefore, due to the lack of support (check can i use), ensure that encapsulation is set to ViewEncapsulation.Emulated. This should be the default option.

    Working Plunker:

    @Component({
      selector: 'my-app',
      template: `
        <div>
          <h2>Hover me please</h2>
        </div>
      `,
      styles: [`
        :host(:hover) {
          color: Cyan;
        }
      `],
      encapsulation: ViewEncapsulation.Emulated
    })
    export class App {
      constructor() {
    
      }
    }
    

    The generated HTML will look like:

      <my-app _nghost-c0="" ng-version="4.2.4">
        <div _ngcontent-c0="">
          <h2 _ngcontent-c0="">Hover me please</h2>
        </div>
      </my-app>
    

    And the style like:

    [_nghost-c0]:hover {
      color: Cyan;
    }