首页 > 解决方案 > FormGroup 初始化问题

问题描述

在尝试使用如下所示定义的登录表单运行 Angular 应用程序时,它会引发错误:

src/app/pages/auth/login/login.component.ts:12:3 - 错误 TS2564:属性 'loginForm' 没有初始化程序,并且未在构造函数中明确分配。

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { AuthService } from '../../../services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  loginForm: FormGroup;

  constructor(private authService: AuthService) {}

  ngOnInit() {
    this.loginForm = new FormGroup({
      email: new FormControl('', {
        validators: [Validators.required, Validators.email]
      }),
      password: new FormControl('', { validators: [Validators.required] })
    });
  }

  onSubmit() {
    this.authService.login({
      email: this.loginForm.value.email,
      password: this.loginForm.value.password
    });
    console.log("logging in...");
  }

}

有谁知道初始化 FormGroup 的正确方法是什么?

标签: angular

解决方案


根据错误消息在构造函数中执行此操作:

constructor(private authService: AuthService) {
  this.loginForm = new FormGroup({
    email: new FormControl('', {
      validators: [Validators.required, Validators.email]
    }),
    password: new FormControl('', { validators: [Validators.required] })
  });
}

或者你可以在你的类定义中初始化它:

loginForm = new FormGroup({
  email: new FormControl('', {
    validators: [Validators.required, Validators.email]
  }),
  password: new FormControl('', { validators: [Validators.required] })
});

这与 没有特别相关FormGroup,它是一个 TypeScript 设置,不允许在类定义或构造函数中定义不可为空的属性。

如果您不喜欢此设置,您可以修改您的tsconfig.json以将其包含在compilerOptions

"strictPropertyInitialization": false

这将允许您不在构造函数中初始化属性,但如果您忘记这样做也不会警告您。您真正需要记住的唯一一件事是@Input()绑定在构造函数中尚未准备好,因此在构建表单时不要尝试使用它们。使用它们在构建表单后修改或设置表单的值。


推荐阅读