angulartypescriptangular-formsangular14

Type 'string' is not assignable to type 'FormGroup<any>' Angular 14 error


I am a beginner Angular developer, I was building a todoList App using this tutorial -> https://www.youtube.com/watch?v=WTn2nVphSl8 It was done using Angular 13. Where i am getting an error is in the todo.component.html , it looks like this

<mat-card class="mt-3 ">
                    <form [ formGroup ] = "todoForm" >
                            <mat-form-field appearance="outline" style="width: 100%; ">
                              <mat-label>Task Name</mat-label>
                              <input formControlName="item" matInput placeholder="Placeholder">
                              <mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
                              <mat-hint>Add task name</mat-hint>
                              
                            </mat-form-field>
                            <button mat-stroked-button color="primary" > Add</button>
                    </form>
                </mat-card>

and my todo.component.ts looks like this

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators} from '@angular/forms';

@Component({
  selector: 'app-todo',
  templateUrl: './todo.component.html',
  styleUrls: ['./todo.component.scss']
})
export class TodoComponent implements OnInit {
  todoForm !: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.todoForm = this.fb.group({
      item : ['', Validators.required],
    })
  }

}

As i was researching i found a lot of reactive forms being implemented using form control, i tried that method but it did not work. the error remained the same. How best can I resolve this. Is it that i am missing something in my todo.component.html or i am supposed to review the way i defined my form in todo.component.ts?


Solution

  • Looks like the spaces in somehow cause the binding not to work as expected. Remove the spaces, i.e. [formGroup] instead of [ formGroup ] in between the square brackets and it should work as expected.

      <form [formGroup] = "todoForm" >
        <!-- Rest of your code -->
      </form>