typescript 为什么'$event.target.checked'在我尝试将其与mat-checkbox一起使用时给出angular TypeError

o2g1uqev  于 2023-04-13  发布在  TypeScript
关注(0)|答案(3)|浏览(156)

当我尝试使用$event.target.checked with angular mat-checkbox时,它给出了一个错误,即“Cannot read property 'checked' of undefined at Object.eval [as handleEvent]”这是为Angular 8上的复选框传递多个值

onChange(cls: string, isChecked: boolean) {
  const clsFormArray = < FormArray > this.myForm.controls.usercls;
  if (isChecked) {
    clsFormArray.push(new FormControl(cls));
  } else {
    let index = clsFormArray.controls.findIndex(x => x.value == cls);
    clsFormArray.removeAt(index);
  }

}
<mat-checkbox class="example-margin" (change)="onChange(data.cls, $event.target.checked)">
  {{ data.cls }}
</mat-checkbox>
<mat-checkbox class="example-margin"(change)="onChange(data.cls,$event.target.checked)">
{{ data.cls }}
</mat-checkbox>
    onChange(cls: string, isChecked: boolean) {
            const clsFormArray = <FormArray>this.myForm.controls.usercls;
            if (isChecked) {
              clsFormArray.push(new FormControl(cls));
            } else {
              let index = clsFormArray.controls.findIndex(x => x.value == cls);
              clsFormArray.removeAt(index);
            }
            }

我期望类被推入并添加到数组中,以便我可以打印它

qxsslcnc

qxsslcnc1#

不需要发送target。只需发送$event.checked我已经更新了下面的代码。

<mat-checkbox class="example-margin" (change)="onChange(data.cls, $event.checked)">
  {{ data.cls }}
</mat-checkbox>
zaqlnxep

zaqlnxep2#

<mat-checkbox class="example-margin"(change)="onChange($event)">
{{ data.cls }}
</mat-checkbox>

  onChange(event) {
            const clsFormArray = <FormArray>this.myForm.controls.usercls;
            if (event.checked) {
              clsFormArray.push(new FormControl(event.source.value));
            } else {
              let index = clsFormArray.controls.findIndex(x => x.value == event.source.value);
              clsFormArray.removeAt(index);
            }
            }
6fe3ivhb

6fe3ivhb3#

使用$event.source.value,即使用source代替target。如果source不起作用,请在浏览器中检查您的Web应用程序并检查对象名称,然后使用该对象名称代替target

相关问题