[英]Do I need a setter for two-way binding?
I've created a checkbox with two-way binding to a getter. 我创建了一个具有与吸气剂双向绑定的复选框。 I don't have a setter because the getter will return a result of filtering of a list. 我没有setter,因为getter将返回过滤列表的结果。
Locally this solution works fine but after deployment I get the following error "Cannot set property myProperty of [object Object] which has only a getter at Object.handleEvent" 此解决方案在本地运行良好,但部署后出现以下错误“无法设置[object Object]的属性myProperty,该对象在Object.handleEvent中只有吸气剂”
<input type="checkbox" class="custom-control-input" id="myId" [(ngModel)]="myProperty" (change)="toggleSelection($event)"/>
public get myProperty(): boolean {
return this.list.every(function(item: any) {
return item.selected == true;
});
}
toggleSelection(event) {
this.list.forEach(h => (h.selected = event.target.checked));
}
I try to understand what is going on. 我试图了解发生了什么。 When I create a setter and remove the change event it will work after deployment. 当我创建设置器并删除更改事件时,它将在部署后起作用。
<input type="checkbox" class="custom-control-input" id="myId"[(ngModel)]="myProperty""/>
public set myProperty(checked: boolean) {
this.list.forEach(h => (h.selected = checked));
}
public get myProperty(): boolean {
return this.list.every(function(item: any) {
return item.selected == true;
});
}
Now I want to understand why the first implementation works locally. 现在,我想了解为什么第一个实现在本地有效。 Locally I don't need a setter but after deployment (a build) it needs a setter. 在本地,我不需要二传手,但是在部署(构建)后,它需要二传手。
In angular, two ways binding means: 从角度上讲,绑定的两种方式表示:
Therefore the right using in Angular for two ways binding is when you need to get & set. 因此,在Angular中以两种方式使用绑定的权利是当您需要获取和设置时。 In my opinion, in your case you should use the option of one-way binding - variable that changes the HTML, like that: 我认为,在您的情况下,应使用单向绑定选项-更改HTML的变量,如下所示:
<input type="checkbox" class="custom-control-input" id="myId"
[checked]="myProperty" (change)="toggleSelection($event)"/>
public get myProperty(): boolean {
return this.list.every(function(item: any) {
return item.selected == true;
});
}
toggleSelection(event) {
this.list.forEach(h => (h.selected = event.target.checked));
}
This is the right way in the concept of Angular. 这是Angular概念中的正确方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.