2016-12-07 90 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 
     } 

的是,當調整了大小的窗口,獲取當前信息的身體姿勢