[英]Set variable programmatically without triggering onChange
我在离子中有以下切换:
<ion-toggle (ionChange)="changeConfirmation($event)" [(ngModel)]="check" color="tertiary">
这是 changeConfirmation changeConfirmation()
function。
changeConfirmation(event) { // should only happen when manually toggled
this.user.changeConfirmation(this.date, this.check, this.userData)
this.toast.showToast(`Your name has been ${this.check ? 'added to' : 'removed from'} the list`, 'top')
}
当组件根据我从数据库检索的数据呈现时,切换值在我的代码中设置为 true/false。 设置变量后,由于ionChange
function 也会调用 changeConfirmation changeConfirmation()
function。 如果用户手动切换切换,我怎么能只调用这个 function?
我建议 go 反应。 它具有很酷的功能,包括您现在正在寻找的...即当以编程方式设置值时,您可以定义它不会触发事件,在这种情况下是表单控件的valueChanges
。 顺便说一句,如果这是一个表单,我会进一步建议您继续使用响应式表单:但是让我们在这里使用一个“简单”的表单控件:
import { FormControl } from '@angular/forms';
// ...
myToggle = new FormControl();
formCtrlSub = new Subscription();
constructor() {
// is fired when value changes
this.formCtrlSub = this.myToggle.valueChanges.subscribe((value: boolean) => {
console.log('user changed value!')
})
}
// for testing setting value in Onit
// set the boolean value using setValue()
// adding emitEvent:false will not trigger valueChanges
ngOnInit() {
this.myToggle.setValue(true, { emitEvent: false})
}
ngOnDestroy() {
// remember to unsubscribe!!
this.formCtrlSub.unsubscribe();
}
然后在模板中附加表单控件,您可以删除ionChange
因为我们正在监听valueChanges
:
<ion-toggle [formControl]="myToggle"></ion-toggle>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.