Angular 2:Bootstrap Switch不改变变量值 [英] Angular 2: Bootstrap Switch not changing value of variable
问题描述
我在Angular 2应用程序中使用bootstap开关作为复选框。当你点击开关时,我希望我班级中的 LightNeeded
变量的值随之改变。我有以下代码:
I'm using bootstap switches for checkboxes in my Angular 2 application. When you click on the switch, I want the value of my LightNeeded
variable in my class to change along with it. I have the following code:
HTML:
<input class="bootstrap-switch light-needed" name="LightNeeded" type="checkbox" [(ngModel)]="LightNeeded">
TypeScript文件:
TypeScript file:
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
变量的值。
When switch is true, it successfully logs true to the console. When it is false, it successfully logs false to the console. However, it never changes the value of my LightNeeded
variable.
当我将鼠标悬停在上时这
的 this.LightNeeded
,我收到以下警告:
When I hover over this
of this.LightNeeded
, I get the following warning:
可疑'this'用法:在当前上下文中'this'指的是本地
函数,而不是包含类。
suspicious 'this' usage: in current context 'this' refers to a local function, not to a containing class.
我如何获得此
以我想要的方式工作并更改我的 LightNeeded
的值变量?我愿意采取其他有意义的方法。我尝试将 [attr.checked] =LightNeeded?true:null
添加到我的输入中,但它无效。
How can I get this
to work the way I am intending and change the value of my LightNeeded
variable? I'm open to taking other approaches that make sense too. I tried adding [attr.checked]="LightNeeded? true : null"
to my input, but it didn't work.
编辑:
添加 [(ngModel)] =LightNeeded的双向绑定
在它是一个简单的复选框时工作,但由于某种原因,引导开关插件打破了双向绑定。其他插件,如JQuery Inputmask和JQuery UI Datepicker也会破坏双向绑定。
The two-way binding from adding [(ngModel)]="LightNeeded"
worked when it was a simple checkbox, but for some reason the bootstrap switch plugin breaks that two-way binding. Other plugins such as JQuery Inputmask and JQuery UI Datepicker also break two-way binding.
推荐答案
您的事件处理函数会更改上下文此
。相反,您应该使用箭头函数,它不会更改上下文/绑定。请参阅 https://developer.mozilla.org/en -US / docs / Web / JavaScript / Reference / Functions / Arrow_functions
Your event handler function changes the context of this
. Instead, you should use an arrow function, which does not change context/binding. See 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;
};
});
这篇关于Angular 2:Bootstrap Switch不改变变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!