2017-01-17 101 views
2

我的目標是根據組件布爾值與Angular 2設置或刪除類。例如:isRed = true>如果isRed = false>添加class「red」>刪除class「red」。這怎麼可能?代碼嘗試:Angular 2有條件地添加類

isRed: boolean; 

constructor() { 
    $(document).scroll(function(){ 
     var scrollTop = $(this).scrollTop(); 
     if(window.location.hash) { 

     } else{ 
      this.isRed = true; 
     } 
     if(scrollTop > 50) { 
      this.isRed = true; 
     } 
     else { 
      this.isRed = false; 
     } 
    }); 
} 

和HTML:

[ngClass]="{red: isRed}" 
+0

您的代碼應該工作,不是嗎? –

+0

構造函數中的不同變量是否爲複製/粘貼問題?如果不是'isRed'可能總是未定義。 – Philipp

+0

能否請您分享更多的代碼(滿級和模板) –

回答

7

最簡潔的方式是恕我直言

[class.red]="isRed" 

更新

你的問題的原因是function

$(document).scroll(function(){ 

它應該使用箭頭功能

$(document).scroll(() => { 

否則this的回調中不會指向當前類的,而是給調用者。

我建議你儘量避免使用Angular2的jQuery。改用

class MyComponent { 

    constructor(private elRef:ElementRef) {} 

    isRed:boolean; 

    @HostListener('document:scroll', ['$event']) 
    onScroll(event:any) { 
    var scrollTop = this.elRef.nativeElement.scrollTop; 
    // or 
    $(this.elRef.nativeElement).scrollTop(); 

    if(window.location.hash) { 

    } else{ 
     this.isRed = true; 
    } 
    if(scrollTop > 50) { 
     this.isRed = true; 
    } 
    else { 
     this.isRed = false; 
    } 
    } 
} 
+0

不工作.... – TeodorKolev

+0

'isRed' <->'isRead'由@Phillip –

+0

提到它是不是從 – TeodorKolev

-1

這是JavaScript的,所以我會嘗試這樣的:

isRed; // there's no need to initialize this variable 
      since the constructor has its own scope but hey, 
      do it if you wish so 

此外,它似乎並不認爲你是一個對象容器內工作,因爲你正在使用;代替這意味着你不應該使用「」,而是「=