html - Angular 6 Forms TypeError:无法读取null的属性“有效”
问题描述
我有一个带有两个 FormControls 的简单表单,我在其中订阅了所有 valueChanges。但是在检查错误时,我得到了这个错误:
请注意,我首先能够记录输入,但之后是null
.
打字稿
export class Component {
@Input() product: Product;
form: FormGroup;
errors: any;
messages: any;
constructor(
private fb: FormBuilder,
) { }
ngOnInit(): void {
this.setupMessages();
this.form = this.fb.group({
name: ['', [
Validators.required,
Validators.minLength(3),
Validators.maxLength(100),
]],
description: ['', [
Validators.maxLength(10000),
]],
});
this.form.patchValue(this.product);
this.form.valueChanges.subscribe(data => this.checkErrors());
}
private checkErrors(): void {
for (let field in this.errors) {
this.errors[field] = '';
let input = this.form.get(field);
// I am able to log input
// but input.valid is null
if (!input.valid) {
for (let error in input.errors) {
this.errors[field] = this.messages[field][error];
}
}
}
}
private setupMessages(): void {
this.messages = {
name: {
required: 'Please give your product an awesome name',
minlength: 'The name should be longer than 3 characters',
maxlength: 'Keep your product name under 100 characters',
},
description: {
maxlength: 'Your description is to long',
},
}
this.errors = {
name: '',
descripton: '',
}
}
}
HTML
<form [formGroup]="form">
<dy-input
[required]="true"
[placeholder]="'Give your product an awesome name'"
formControlName="name"
[error]="errors.name"
[maxlength]="100"
>
Name
</dy-input>
<dy-textarea
[placeholder]="'Pointing out details helps to improve sales'"
[error]="errors.description"
formControlName="description"
[height]="'480px'"
[maxlength]="10000"
>
Description
</dy-textarea>
</form>
如您所见,我正在使用自己的自定义表单控件。但我很确定,问题不是由它们引起的,因为事实上它们不会导致其他形式的任何错误。
解决方案
第二次,您的输入为空,因为您的错误中有错字。
private setupMessages(): void {
this.messages = {
name: {
required: 'Please give your product an awesome name',
minlength: 'The name should be longer than 3 characters',
maxlength: 'Keep your product name under 100 characters',
},
description: {
maxlength: 'Your description is to long',
},
}
this.errors = {
name: '',
descripton: '',
}
}
请注意,在 中,您有一个名为descriptonthis.errors
的错误键,但您的表单组键是description(拼写正确)。
您在版本中缺少ithis.errors
。
此外,除了我上面的评论之外,也许值得编辑您的条件以if (input && !input.valid)
确保其安全:)
推荐阅读
- linux - Linux中目录的权限继承
- reactjs - TypeError:无法读取未定义 Nextjs 的属性“地图”?
- c++ - C++ 中的 C。是 C 还是 C++?
- reactjs - 在 create-react-app 应用程序中代理请求
- java - Google Protobuf 处理空值
- c# - 为表“Tarefas”指定了多个标识列。每个表只允许一个标识列错误
- python - 将字符串转换为数组,然后为熊猫求和错误
- postgresql - 无法创建目录“/var/lib/postgresql/data”:文件存在
- assembly - 在 Thumb 模式下将寄存器符号扩展为 64 位(设置所有位 = 符号位)
- windows - OpenSSH 多平台配置 - 如何避免 Match exec 错误消息?