angular - 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 的正确方法是什么?
解决方案
根据错误消息在构造函数中执行此操作:
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()
绑定在构造函数中尚未准备好,因此在构建表单时不要尝试使用它们。使用它们在构建表单后修改或设置表单的值。
推荐阅读
- google-bigquery - Big Query Deduplication 查询示例说明
- f# - F# 中的结果和域设计
- c# - 如何在不使用“使用 System.Security.Cryptography;”的情况下在字符串上实现 md5;或任何其他内置方法 - C#
- wordpress - 如何防止用户(作者)在单个帖子中添加新标签?
- haskell - “忽略(可能损坏)包的 abi-depends 字段”是什么意思?
- javascript - 如何通过ts中的变量获取属性
- ios - ios中的离子推送通知
- python - 数据框python删除重复项
- ios - 为 Flutter iOS 项目生成一个用于测试目的的 diawi 链接
- javascript - Jquery 自动完成返回表中的所有行,而 PHP 根据查询返回结果