【发布时间】:2019-10-16 09:42:02
【问题描述】:
我有一个带有复选框列表 (mat-checkbox) 的 Angular 应用程序,它可以根据区域设置正确显示英语或西班牙语值。
问题:但是,当用户单击复选框时,复选框本身并没有被始终选中。它似乎需要双击。什么可能导致这样的事情?
我试过了:
- 我已经查看了 [checkex] 和 (change)。
- 我已尝试更改我的 对象/类/接口。
- 我查看了 Angular 文档。
- 我已经在我能找到的所有内容上完成了 console.log
- 我浏览了 SO 文章,例如: Mat-checkbox checked not changing checkbox state
component.html:
<div class="student-history-checkbox" *ngFor="let item of gradesInCurrentLanguage()">
<mat-checkbox [checked]="isChecked(item.ID)" (change)="onChangeCB($event, item.ID)">{{item.Value}}</mat-checkbox>
</div>
component.ts:
public gradesInCurrentLanguage() : CGenericRecord[] {
return this.ms.XFormForLocale(this.grades, this.localeId);
}
isChecked(ID : number)
{
return (this.gradeInfo.Grades.indexOf(ID) > -1) ? true : false;
}
onChangeCB(event : any, id : number)
{
if(event.checked && this.gradeInfo.Grades.indexOf(id) == -1){
this.gradeInfo.Grades.push(id);
}else{
let index = this.gradeInfo.Grades.indexOf(id);
this.gradeInfo.Grades.splice(index, 1);
}
}
interface.ts:
export class CGenericRecord
{
constructor(
public ID: number,
public Value: string)
{}
}
export interface GenericTranslationRecord {
ID : number,
Value : string,
SpanishValue: string
}
service.ts:
public XFormForLocale(grades: GenericTranslationRecord[], localeId: string) : CGenericRecord[] {
let recs :CGenericRecord[] = [];
for (let g of grades)
{
recs.push( new CGenericRecord(d.ID, localeId === "es" ? d.SpanishValue : d.Value));
}
return recs;
}
预期结果:当用户单击一次复选框时,复选框应显示已选中。还应该显示一键取消勾选。
实际结果:复选框仅在多次点击后才被选中
【问题讨论】:
-
不使用 [checked],只需使用 [(ngModel)]="variable" 并将变量更改为 true/false。实际上,每次更改推送和切片数组的效率都不是很高。更好,例如使用 getter
get selected(){return item.filter(x=>x.selected).map(o=>o.id)}- 或者不使用 getter 并且只调用一次函数-
标签: angular typescript events checkbox