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

In0*_*enT 5 angular angular-reactive-forms

我曾经有一个没有任何验证的简单表单,其中的 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>
Run Code Online (Sandbox Code Playgroud)

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

HTMl 的当前部分:

<form [formGroup]="todoForm">
    <mat-form-field>
        <input matInput
               placeholder="TaskName"
               formControlName="taskName"
               required
               [(ngModel)]="todoListService.toDoData.taskName"
        >
    </mat-form-field>
Run Code Online (Sandbox Code Playgroud)

所以我删除了 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();
    }
Run Code Online (Sandbox Code Playgroud)

我从中得到的错误是:

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'.
Run Code Online (Sandbox Code Playgroud)

显然,我误解了从表单访问数据的一些事情。

我一直在关注本指南和这个例子:

https://angular.io/api/forms/FormControlName#use-with-ngmodel https://stackblitz.com/edit/example-angular-material-reactive-form

谢谢你的帮助!

The*_*ram 3

这里this.todoForm.get('controlname')返回 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();
    }
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助!