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

时间:2019-02-14 14:14:00

标签: 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>

然后,我将表单移至反应形式,并收到警告,说我不能将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://stackblitz.com/edit/example-angular-material-reactive-form

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

这里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();
    }

希望这会有所帮助!

答案 1 :(得分:0)

从Angular 7开始,您不能同时使用formControlName和ngModel。如果要使用模板驱动的表单,则可以使用ngModel,如果要使用反应性表单,则不能使用ngModel。 (简单)

如果您决定遵循反应形式的方法:

在HTML中:

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

在TS中:

selectedCode: string = "";

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

答案 2 :(得分:0)

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

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

    this.todoForm.patchValue({
      taskName: this.todoListService.toDoData.taskName
    });
相关问题