Angular – ngModel on the same form field as formControlName

angularangular-reactive-forms

I used to have a simple form without any validation where the HTML roughly looked like this:

<mat-form-field>
        <input matInput
               type="text"
               placeholder="TaskName"
               [(ngModel)]="todoListService.toDoData.taskName"
               formControlName="taskName"
               required
               required>
               [(ngModel)]="todoListService.toDoData.taskName"
        >
    </mat-form-field>

I then moved my form to reactive forms and received the warning that I can't have ngModel on the same field as formControlname. Struggling how I'm supposed to assign the data from the form to the input field of the service.

Current section of HTMl:

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

So I removed the ngModel line and added this to my 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();
    }

The errors I'm getting from that are:

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'.

Apparently, I misunderstood something about accessing data from the form.

I have been following this guide and this example:

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

Thanks for any help!

Best Answer

From Angular 7 and onward you can't use both formControlName and ngModel together. If you want to use template-driven forms you can go with ngModel and if you want to use reactive forms you can't go with ngModel. (Simple)

AS you have decided to follow reactive forms approach:

In HTML:

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

In TS:

selectedCode: string = "";

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