Angular 2有条件地添加类

时间:2017-01-17 14:32:48

标签: javascript angular ng-class

我的目标是根据具有Angular 2的组件布尔值来设置或删除类。例如:isRed = true>添加类"红色",如果isRed = false>删除课程"红色"。怎么可能?代码尝试了:

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

2 个答案:

答案 0 :(得分:8)

最简洁的方法是恕我直言

[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;
    }
  }
}

答案 1 :(得分:-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

此外,您似乎没有在对象内部工作,因为您使用; 而不是,这意味着您不应该使用“:< / strong>“而是” =