2016-12-07 95 views
3

如何获取css属性而不是Angular2中的类?绑定到主机的css属性(而不是类)

我有以下代码:

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" 
    } 
} 

风格responsive.css:

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

所以,你可以看到,页面上会每当用户缩小窗口时,相对于身体添加位置。

我只想在我的Angular组件中获取这些信息。如果window大于1024px,hostPosition应该是未定义的,如果小于这个值,则为'相对'。

如何实现这一目标?

回答

1

@HostBinding()应通知不阅读,只为写作。

您可以使用

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

获得分配的元素style.positionhostPosition的价值,但不读取当前style.posotion

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

那么,这并不完全回答我的问题。所以你的意思是不可能实现我想要的? – user3483282

+0

你想要什么?你当然可以阅读'nativeElement.style.position'而不是'nativeElement.offsetLeft'。 –

+0

问题是我不想获取元素的样式。 'this.elRef.nativeElement.style.position'总是空的(“”),因为这似乎得到了style属性中的内容,而不是影响元素的某些类。 我也试过检查'document.body.style.position',但它是一样的东西,我需要的是类似于jQuery函数'$(“body”).css(“position”)' – user3483282

0

不知道这会工作,但是值得一试:

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

的是,当调整了大小的窗口,获取当前信息的身体姿势