【发布时间】:2022-01-11 05:45:06
【问题描述】:
我正在尝试对我的复选框进行必要的验证。
我的 TS 文件:
public colors: Array<any> = [
{ description: 'White', value: 'White' },
{ description: 'Black', value: 'Black' },
{ description: 'Blue', value: 'Blue' },
{ description: 'Green', value: 'Green' },
{ description: 'Yellow', value: 'Yellow' },
{ description: 'Red', value: 'Red' },
];
constructor(
private formBuilder: FormBuilder,
private heroService: HeroService,
private toastr: ToastrService
) {
this.fromInit();
}
ngOnInit(): void {}
fromInit() {
this.heroCreateForm = this.formBuilder.group({
suitColors: new FormArray([], [Validators.required]),
});
}
onCheckChange(event) {
const formArray: FormArray = this.heroCreateForm.get(
'suitColors'
) as FormArray;
if (event.target.checked) {
formArray.push(new FormControl(event.target.value));
} else {
let i: number = 0;
formArray.controls.forEach((ctrl: FormControl) => {
if (ctrl.value == event.target.value) {
formArray.removeAt(i);
return;
}
i++;
});
}
}
invalidSuitColorsMessage() {
// this function doesn't work
if (this.suitColors.errors?.required)
return "You must choose the hero's suit colors";
}
我的 HTML 文件:
<div class="main-content">
<form [formGroup]="heroCreateForm" (ngSubmit)="createHero()">
<div class="container">
<div class="input-container-suitColors-input">
<label><b>Suit colors: </b></label>
<ng-container *ngFor="let color of colors; let i=index">
<div class="radio-contatiner">
<input type="checkbox"
[value]="color.value"
(change)="onCheckChange($event)">
{{color.description}}
</div>
</ng-container>
</div>
<div class="invalid-input-message"
*ngIf="suitColors.touched && suitColors.invalid">{{invalidSuitColorsMessage()}}</div>
// here is the issue. I'm getting here an error
<hr>
<button type="submit"
class="registerbtn"
[disabled]="heroCreateForm.invalid">Register</button>
</div>
</form>
</div>
错误
无法读取未定义的属性(读取 'touched')
我确实明白它为什么会起作用。我在网上搜索并没有找到任何解决我的问题的方法。
如果这些复选框上发生所需的错误,我正在尝试显示一条消息
有没有人可以看一下并向我解释为什么会发生这种情况以及我应该如何解决它?
【问题讨论】:
-
这能回答你的问题吗? Detecting an undefined object property
-
您好,我并没有从这些文章中找到任何解决方法,您将如何进行验证?
-
让我来回答一下如何解决它
标签: angular angular-reactive-forms