You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 15响应式表单属性绑定报错及解决方法

Angular 15响应式表单属性绑定报错解决

报错截图

报错截图1
报错截图2

问题场景

我是Angular新手,在Angular 15中尝试将响应式表单与属性绑定时出现上述报错,尝试多种方法仍无法完成属性绑定。

相关代码

组件TS代码

import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, FormsModule} from "@angular/forms";
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit{
  
  loginVal:FormGroup;

  constructor(private fb : FormBuilder ){
    this.formBinding();
  }

  ngOnInit(): void { };

  formBinding(){
    this.loginVal = this.fb.group({
      username:["testuser"],
      userpass:[""],
    });
  }

  display(){
    console.log(this.loginVal.value);
  }
}

HTML模板代码

<form [formGroup]="loginVal" class="form-group" (ngSubmit)="display()"> 
    <label for="">User Name:</label>
    <input formControlName="username" class="form-control">
    <label for="">Password:</label>
    <input formControlName="userpass" class="form-control">
  
    <button type="submit">Submit</button>
</form>

AppModule导入配置

imports: [
    BrowserModule,
    AppRoutingModule,
    MatSidenavModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule
  ],

解决方法

最终通过**空值断言运算符(!)**解决问题,只需修改组件中loginVal的声明:

loginVal!: FormGroup;

内容的提问来源于stack exchange,提问作者MinhajBoss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 20:25:27