ngModel 与 formControlName 位于同一表单字段上

2024-02-13

我曾经有一个没有任何验证的简单表单,其中 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

谢谢你的帮助!


从 Angular 7 及更高版本开始,您不能同时使用 formControlName 和 ngModel。如果你想使用模板驱动的表单你可以使用 ngModel 如果你想使用反应形式你不能使用 ngModel。 (简单的)

既然你决定跟随反应形式方法:

In HTML:

<input type="text" (change)="onChangeCode($event.target.value)" formControlName="code" id="txtCode">

In TS:

selectedCode: string = "";

onChangeCode(code: string) {
   this.selectedCode = code;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ngModel 与 formControlName 位于同一表单字段上 的相关文章

随机推荐