title: Angular 2 Directive inside html body tag
body: <p>I am trying to create a directive that I can use inside of the html body element.</p>
  
  <p>The purpose of this directive is to add or remove a class.</p>
  
  <p>There must be a service that determine if the class should be visible or not, because I will need to control this from different components.</p>
  
  <p><strong>Question:</strong> How do i toggle the class on my body element with the help of my service.</p>
  
  <p><strong>sticky-search.directive.ts</strong> </p>
  
  <pre><code>import { Directive, HostBinding, Inject, HostListener } from '@angular/core';
  import { DOCUMENT } from '@angular/platform-browser';
  
  import { SearchService } from '../shared/search.service';
  
  @Directive({
    selector: '[mhStickySearch]'
  })
  export class StickySearchDirective {
  
    @HostBinding('class') onStickySearch() {
      return this.searchService.isSearchSticky ? 'search-sticky' : '';
    }
  
    @HostListener('window:scroll', []) onWindowScroll() {
      let number = this.document.body.scrollTop;
  
      if (number &gt;= 65) {
        this.searchService.enableStickySearch();
      } else {
        this.searchService.disableStickySearch();
      }
    }
  
    constructor(private searchService: SearchService, @Inject(DOCUMENT) private document: any) { }
  }
  </code></pre>
  
  <p>The following directive's @Hostlistner is <strong>not</strong> triggering if i put it inside the body tag. But if i place it as a parent the @HostListner is triggered but no class is displaying. </p>
  
  <p>Here is my body tag that the <code>AppComponent</code> uses <strong>as a selector</strong> but that lays as a <strong>parent</strong> of the component</p>
  
  <pre><code>&lt;body class="full-width" mhStickySearch&gt;
  </code></pre>
  
  <p><strong>search.service.ts</strong></p>
  
  <pre><code>import { Injectable } from '@angular/core';
  
  @Injectable() export class SearchService {
  
    isSearchSticky: boolean;
  
    enableStickySearch() {
      this.isSearchSticky = true;   
    }
  
    disableStickySearch() {
      this.isSearchSticky = false;   
    }
  
    constructor() { }
  
  }
  </code></pre>
  
  <p>The <code>SearchService</code> is provided in the <code>AppComponent</code>.
  The service is executed from my <code>HeaderComponent</code> like this:</p>
  
  <pre><code>import { Component } from '@angular/core';
  import { SearchService } from '../../search/shared/search.service';
  
  @Component({
    selector: 'mh-header',
    templateUrl: './header.component.html'
  })
  export class HeaderComponent {
    constructor(private searchService: SearchService) {}
  
    openMobileMenu() {
      this.searchService.enableStickySearch();
    }
  
    closeMobileMenu() {
      this.searchService.disableStickySearch();
    }
  }
  </code></pre>