Angular 2:Bootstrap Switch不改变变量值

时间:2016-11-09 23:13:43

标签: jquery angular typescript bootstrap-switch

我在Angular 2应用程序中使用bootstap开关作为复选框。当您单击开关时,我希望我班级中LightNeeded变量的值随之改变。我有以下代码:

HTML:

<input class="bootstrap-switch light-needed" name="LightNeeded" type="checkbox" [(ngModel)]="LightNeeded">

TypeScript文件:

LightNeeded: boolean;

 ngOnInit(): void {        
    // Invoke bootstrap switches
    $('.bootstrap-switch').bootstrapSwitch({
        onText: "Yes",
        offText: "No"
    });
    this.changeBootstrapSwitchValues();
}

changeBootstrapSwitchValues() {
    $('.light-needed').on('switchChange.bootstrapSwitch', function (event:any, state:any) {
        if (state) {  
            console.log('true');
            this.LightNeeded= true;
        } else {  
            console.log('false');
            this.LightNeeded= false;
        };
    });
}

当switch为true时,它成功将true记录到控制台。如果为false,则成功将false记录到控制台。但是,它永远不会更改LightNeeded变量的值。

当我将鼠标悬停在this的{​​{1}}上时,会收到以下警告:

  

可疑&#39;这个&#39;用法:在目前的情况下,这个&#39;是指当地人   功能,而不是包含类。

如何让this.LightNeeded以我想要的方式工作并更改this变量的值?我也愿意接受其他有意义的方法。我尝试将LightNeeded添加到我的输入中,但它没有用。

修改

添加[attr.checked]="LightNeeded? true : null"的双向绑定在它是一个简单的复选框时起作用,但由于某种原因,引导开关插件会破坏双向绑定。其他插件,如JQuery Inputmask和JQuery UI Datepicker也会破坏双向绑定。

3 个答案:

答案 0 :(得分:1)

您的事件处理函数会更改this的上下文。相反,您应该使用箭头函数,它不会更改上下文/绑定。见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

示例:

$('.light-needed').on('switchChange.bootstrapSwitch', (event:any, state:any) => {
        if (state) {  
            console.log('true');
            this.LightNeeded= true;
        } else {  
            console.log('false');
            this.LightNeeded= false;
        };
    });

答案 1 :(得分:1)

这都是关于功能范围的。 this函数中的changeBootstrapSwitchValues()关键字是指JQuery对象。您可以使用以下技术解决此问题;

changeBootstrapSwitchValues() {
let self = this;
    $('.light-needed').on('switchChange.bootstrapSwitch', function (event:any, state:any) {
        if (state) {  
            console.log('true');
            //this.LightNeeded= true;
            self.LightNeeded= true;
        } else {  
            console.log('false');
            //this.LightNeeded= false;
            self.LightNeeded= false;
        };
    });
}

答案 2 :(得分:0)

也许是迟到但我为angular2 +制作了一个名为jw-boostrap-switch-ng2的组件,如果有人想要查看的话。

是实现组件的更好解决方案,因为您不必担心JQUERY。