【发布时间】:2022-01-11 16:07:23
【问题描述】:
我正在尝试创建一个表单,用户可以在其中选择多种颜色,然后提交表单。
代码
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
) {
this.fromInit();
}
ngOnInit(): void {}
fromInit() {
this.form = this.formBuilder.group({
colors: this.formBuilder.array([], [Validators.required]),
});
}
onCheckChange(event) {
const formArray: FormArray = this.form.get(
'colors'
) 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++;
});
}
}
invalidColorsMessage() {
if (this.form.controls['colors'].errors?.required)
return "You must choose a color";
}
HTML
<div class="invalid-input-message"
*ngIf="this.form.controls['colors'].touched &&
this.form.controls['colors'].invalid">
{{invalidColorsMessage()}}</div>
我遇到的 this.form.controls['colors'] 的属性“touched”总是错误的。无论我选择几个复选框还是不选择任何东西,'touched' 的值总是 false。
我真的不明白为什么当我选中和取消选中复选框时它总是错误的。
预期的结果是,每当有人选中和取消选中复选框并将所有复选框留空时,都会显示一条错误消息。
我想知道为什么 this.form.controls['colors'].touched 的值无论如何总是假的。所以我尝试在网上搜索答案,但不幸的是没有成功找到解决方案。
这里是复选框的演示:https://stackblitz.com/edit/angular-ivy-s8rc6j?file=src/app/app.component.html
谢谢
【问题讨论】:
-
在模板中使用
this毫无意义。你可以写*ngIf="form.controls['colors'].touched && ..."
标签: javascript angular angular-reactive-forms