Chrillewoodz
Chrillewoodz

Reputation: 28328

How to bind a style to an element outside of the component using HostBinding

I'd like to add overflow:hidden/visible to the body tag depending on whether a modal is visible or not. I'd like to achieve this with @HostBinding if possible but I don't know how.

Something like this is what I want:

constructor(private _modalApi: ModalApiService) {

  _modalApi.isOpen$.subscribe(
    modal => {
      this.overflow = this.isOpen ? 'hidden' : 'visible';
    }
  )
}

@HostBinding('body.style.overflow')
overflow: string;

I realise that @HostBinding binds to the host element which in this case would be the modal, but since @HostListener can listen to the document, window etc I thought that there might be a similar use case here.

Is this possible or do I have to make some weird workaround?

Note that I've looked at other questions suggesting to put your app component on the body tag and then doing it via the app component, however, I can't rely on another component since the idea is that this component shouldn't know about any app's structure and still work.

Upvotes: 1

Views: 775

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657268

This is not supported. As HostBinding indicates it binds to the host element of the component, not some arbitrary element.

The document:xxx, window:xxx, or body:xxx targets of the HostListener decorator is special.

You can use plain DOM access as a workaround or some other way to get an ElementRef and use the Renderer to apply styles or other settings.

Upvotes: 2

Related Questions