user3483282
user3483282

Reputation: 55

Bind to host's css property (and not class)

How do I get a css property and not a class in Angular2?

I have the following code:

app.component.ts:

import { Component, HostBinding } from '@angular/core';

@Component({
    selector: 'body',
    templateUrl: 'views/masterpage.html'
})
export class AppComponent {
    @HostBinding('attr.class') hostClass = "sticky-header sidebar-open"; // Works, but not what i want
    @HostBinding('style.position') hostPosition:string; // Does not work

    sidebarToggle() {
        this.sidebarCollapsed = !this.sidebarCollapsed;
        this.hostClass = (this.sidebarCollapsed ? "sidebar-collapsed" : "sticky-header sidebar-open");

        // Here I wanna check what is the 'position' property of my host (body). 
        // See "style-responsive.css"
    }
}

style-responsive.css:

@media screen and (max-width: 1024px) {
    body {
        position: relative;
    }
}

So, as you can see, the page will add the position relative to the body whenever the user shrinks the window.

I just wanna get this information in my Angular component. hostPosition should be undefined if window is larger than 1024px and 'relative' if smaller than that.

How to achieve that?

Upvotes: 3

Views: 1178

Answers (2)

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

Reputation: 657821

@HostBinding() is not for reading, only for writing.

You can use

@HostBinding('style.position') hostPosition:string;

to get the value of hostPosition assigned to the elements style.position, but not to read the current style.posotion.

constructor(private elRef:ElementRef) {
  console.log(elRef.nativeElement.offsetLeft);
  console.log(elRef.nativeElement.offsetTop);
}

Upvotes: 2

kimy82
kimy82

Reputation: 4495

Not sure if that will work, however is worth to try:

@HostListener('window:resize', ['$event'])
      handleClick(event: Event) {
       //Do something when resize window
      }

That should be notified when your window is resized and get current info your body position

Upvotes: 0

Related Questions