角度 11 中代码“$event.target.checked”中的问题

Sup*_*del 5 typescript angular angular11

在我的代码中使用此示例:https://stackblitz.com/edit/angular-rskaug ?file=src%2Fapp%2Fapp.component.html

组件中的 HTML

<td><input type="checkbox" (change)="onChange(employee.id, $event.target.checked)"></td>
Run Code Online (Sandbox Code Playgroud)

组件中的打字稿

onChange(id: any, isChecked: boolean) {
    const idFormArray = <FormArray>this.myForm.controls.employeeRelatedId;

    if (isChecked) {
      idFormArray.push(new FormControl(id));
    } else {
      let index = idFormArray.controls.findIndex(x => x.value == id)
      idFormArray.removeAt(index);
    }
  }
Run Code Online (Sandbox Code Playgroud)

错误详情

类型“EventTarget”上不存在属性“checked”。

45 <input type="checkbox" (change)="onChange(employee.id, $event.target.checked)">

Mic*_*l D 6

鉴于模板中已经有一个反应式表单,我不确定为什么这input不是它的一部分。然后你可以使用类似表单组的valueChanges可观察的东西来监听它的事件。

话虽如此,您可以尝试多种快速修复方法。

选项1:模板引用变量

您可以在元素中使用模板引用变量并在事件处理程序的参数中<input>捕获它的属性。checked

<input type="checkbox" #inputBox (change)="onChange(employee?.id, inputBox?.checked)">
Run Code Online (Sandbox Code Playgroud)

这里#inputBox是模板引用变量。

选项 2:禁用类型检查

您可以使用$any()模板中的函数禁用类型检查。

<input type="checkbox" (change)="onChange(employee?.id, $any($event.target)?.checked)">
Run Code Online (Sandbox Code Playgroud)

安全导航操作符?.用于避免潜在的possibly undefined错误。

更新:工作示例

工作示例:Stackblitz

  • @MuhammadBilal 这是个好主意,OP 创建 stackblitz 示例,其他人分叉了链接!:) (2认同)