gpt4 book ai didi

html - Angular 6 形式类型错误 : Cannot read property 'valid' of null

转载 作者:搜寻专家 更新时间:2023-10-30 21:27:23 24 4
gpt4 key购买 nike

我有一个带有两个 FormControl 的简单表单,我在其中订阅了所有 valueChanges。但是在检查错误时我得到这个错误:enter image description here请注意,我首先能够记录输入,但之后是 null

typescript

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: '',
}
}

请注意,在 this.errors 中,您有一个名为 descripton 的错误键,但您的表单组键是 description(拼写正确)。

您在 this.errors 版本中缺少一个 i

此外,除了我上面的评论之外,也许值得将您的条件编辑为 if (input && !input.valid) 以确保安全 :)

关于html - Angular 6 形式类型错误 : Cannot read property 'valid' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51797956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com