3

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?

2 Answers 2

2

@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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Well, that doesn't quite answer my question. So you mean it's not possible to achieve what I want?
What do you want? You can of course read nativeElement.style.position instead of nativeElement.offsetLeft.
The problem is that I don't want to get the style of the element. this.elRef.nativeElement.style.position is always empty (""), because that seems to get what is in the style property and not in some class that's affecting the element. I have tried also to check document.body.style.position, but it's the same thing, what I need is something like the jQuery function $("body").css("position")
Just found the solution using window.getComputedStyle. I edited the post adding that and marked as answer. Thank you
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.