2016-12-05 72 views
0

我正在試圖給類包含所有我的應用程序的包裝,我經常發現這個方便的給了某些國家如當標題是固定的,或者在菜單的打開等Angular2:指令變量的變化,更新元素

所以通讀一些文件的角度我應該可能使用'指令'。現在,我得到這一切成立,它看起來像這樣:

constructor(private router:Router, @Inject(DOCUMENT) private document:Document, el:ElementRef, renderer:Renderer) { 
    this.setClasses(el, renderer); 
} 

setClasses(el:ElementRef, renderer:Renderer) { 
    renderer.setElementClass(el.nativeElement, 'header-fixed', this.headerFixed); 
} 

@HostListener("window:scroll", [])onWindowScroll() { 
    let number = this.document.body.scrollTop; 

    if (number > 100) { 
     this.headerFixed = true; 
    } else if (this.headerFixed && number < 10) { 
     this.headerFixed = false; 
    } 
} 

現在,這是可以正常使用,但你可以看見我撥動headerFixed變量取決於滾動位置。不過,我當然可以再次運行功能setClasses(),它會工作,但無論如何訂閱/觀看變量並在更改時自動更新?

或者有沒有更好的方法來實現我想要做的掃管笏?

+1

您是否嘗試過使用'@HostBinding( '頭固定')'吸氣劑一起? http://stackoverflow.com/questions/35168683/hostbinding-with-a-variable-class-in-angular2 – yurzui

+0

嗯,工作表示感謝! – LVDM

+0

還有一件事,它有點相關,例如在指令選擇器中,我有一個按鈕來切換menuOpen,如:(click)=「menuOpen =!menuOpen」'在變量聲明中聲明爲'@HostBinding( 'class.menu-open')menuOpen = false;'但它不起作用。任何想法鋤頭最好處理這些事件? – LVDM

回答

2

您可以使用@HostBinding像:

@HostBinding('class.header-fixed') get myClass() { 
    return someCondition; 
} 

Plunker Example

+0

感謝在我的plunker!先查明天早上,我可以得到它的工作。 – LVDM

+0

你welc青梅! – yurzui