【问题标题】:Angular: why does (change) event for checkbox only trigger after double click?Angular:为什么复选框的(更改)事件仅在双击后触发?
【发布时间】: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=&gt;x.selected).map(o=&gt;o.id)} - 或者不使用 getter 并且只调用一次函数-

标签: angular typescript events checkbox


【解决方案1】:

上面的代码导致了一个无限循环。我没有在 ngFor 中使用该方法,而是在 typescript 中创建了一个变量并将其设置为 = 方法。然后我在 HTML 中使用了该变量。现在可以了。

HTML:

<div class="student-history-checkbox" *ngFor="let item of gradesInCurrentLanguageVar">

TS:

this.gradesInCurrentLanguagevar = gradesInCurrentLanguage();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-21
    • 2013-08-03
    • 1970-01-01
    • 2011-06-19
    • 2018-03-20
    • 1970-01-01
    • 2019-06-18
    相关资源
    最近更新 更多