我曾经有一个没有任何验证的简单表单,其中 HTML 大致如下所示:
<mat-form-field>
<input matInput
type="text"
placeholder="TaskName"
[(ngModel)]="todoListService.toDoData.taskName"
formControlName="taskName"
required
required>
[(ngModel)]="todoListService.toDoData.taskName"
>
</mat-form-field>
然后,我将表单移至反应式表单,并收到警告,指出我不能将 ngModel 与 formControlname 放在同一字段上。纠结如何将表单中的数据分配到服务的输入字段。
HTMl 的当前部分:
<form [formGroup]="todoForm">
<mat-form-field>
<input matInput
placeholder="TaskName"
formControlName="taskName"
required
[(ngModel)]="todoListService.toDoData.taskName"
>
</mat-form-field>
所以我删除了 ngModel 行并将其添加到我的 TS 中:
saveToDo() {
this.dialogRef.close();
this.todoListService.toDoData.taskName = this.todoForm.get('taskName');
this.todoListService.toDoData.dueDate = this.todoForm.get('dueDate');
this.todoListService.toDoData.extraNote = this.todoForm.get('extraNote');
this.todoListService.addToDo();
}
我从中得到的错误是:
ERROR in src/app/new-to-do-dialog/new-to-do-dialog.component.ts(31,9): error TS2322: Type 'AbstractControl' is not assignable to type 'string'.
src/app/new-to-do-dialog/new-to-do-dialog.component.ts(32,9): error TS2322: Type 'AbstractControl' is not assignable to type 'DateConstructor'.
Property 'prototype' is missing in type 'AbstractControl'.
src/app/new-to-do-dialog/new-to-do-dialog.component.ts(33,9): error TS2322: Type 'AbstractControl' is not assignable to type 'string'.
显然,我误解了有关从表单访问数据的一些内容。
我一直在遵循本指南和这个示例:
https://angular.io/api/forms/FormControlName#use-with-ngmodel https://angular.io/api/forms/FormControlName#use-with-ngmodel
https://stackblitz.com/edit/example-angular-material-reactive-form https://stackblitz.com/edit/example-angular-material-reactive-form
谢谢你的帮助!