Angular14报错:Type 'string'不可赋值给FormGroup<any>的解决咨询
解决Angular中“Type 'string' is not assignable to type 'FormGroup'”错误
问题根源
你的错误是因为HTML模板里的属性绑定语法错误:[ formGroup ] = "todoForm" 中方括号和指令名formGroup之间存在空格,Angular会将其解析为字符串字面量绑定,而非绑定到组件中定义的todoForm FormGroup实例,从而触发类型不匹配报错。
修复步骤
修正HTML模板的表单绑定语法
将[ formGroup ] = "todoForm"改为[formGroup]="todoForm",去掉方括号与指令名之间的空格:<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>验证必要模块是否导入
确保你的模块(如AppModule或功能模块)中已导入ReactiveFormsModule(响应式表单必备)和Angular Material相关模块:import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { ReactiveFormsModule } from '@angular/forms'; import { MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatButtonModule } from '@angular/material'; import { AppComponent } from './app.component'; import { TodoComponent } from './todo/todo.component'; @NgModule({ declarations: [ AppComponent, TodoComponent ], imports: [ BrowserModule, ReactiveFormsModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatButtonModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
说明
你的todo.component.ts代码是正确的,使用FormBuilder创建FormGroup的方式符合Angular响应式表单规范,无需调整。
内容的提问来源于stack exchange,提问作者Ruth Mazango
相关产品推荐
相关产品推荐

