ngModel 在与 formControlName 相同的表单字段上

ngModel on the same form field as formControlName

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

然后我将我的表单移动到响应式表单并收到警告,我不能在与 formControlname 相同的字段上使用 ngModel。挣扎我应该如何将表单中的数据分配给服务的输入字段。

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://stackblitz.com/edit/example-angular-material-reactive-form

感谢您的帮助!

此处 this.todoForm.get('controlname') returns AbstractControl 对象,因此从对象访问值,如下所示

saveToDo() {
        this.dialogRef.close();
        this.todoListService.toDoData.taskName = this.todoForm.get('taskName').value;
        this.todoListService.toDoData.dueDate = this.todoForm.get('dueDate').value;
        this.todoListService.toDoData.extraNote = this.todoForm.get('extraNote').value;
        this.todoListService.addToDo();
    }

希望这对您有所帮助!

从 Angular 7 开始,您不能同时使用 formControlName 和 ngModel。如果你想使用 template-driven forms 你可以使用 ngModel 如果你想使用 reactive forms 你不能使用ng模型。 (简单)

因为您已决定遵循反应形式方法:

在HTML中:

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

在 TS 中:

selectedCode: string = "";

onChangeCode(code: string) {
   this.selectedCode = code;
}

从 html 文件中删除 [(ngModel)]。

然后将以下内容添加到您的 ts 文件

    this.todoForm.patchValue({
      taskName: this.todoListService.toDoData.taskName
    });