Angular 2+ material mat-chip-list formArray验证
Angular 2+ material mat-chip-list formArray validation
如何验证 mat-chip
已添加到 mat-chip-list
。我正在使用 ReactiveForms。我已经尝试使用 required
验证器。
该值可以是一个姓名列表,因此在提交表单之前,我需要确保我的姓名列表中至少有 1 个姓名。如果列表为空,则 mat-error
应显示错误消息。使用 required
验证器会使表单无效,无论是否将名称添加到列表中。
编辑:反应形式
我已经尝试制作一个自定义验证器,我现在使用的是响应式表单而不是模板驱动的表单,但我无法让它工作。我编辑了以下代码以反映我的更改,并且我创建了这个 https://stackblitz.com/edit/angular-4d5vfj
HTML
<form [formGroup]="myForm">
<mat-form-field class="example-chip-list">
<mat-chip-list #chipList formArrayName="names">
<mat-chip *ngFor="let name of myForm.get('names').controls; let i=index;"
[formGroupName]="i"
[selectable]="selectable"
[removable]="removable"
(removed)="remove(myForm, i)">
<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
</mat-chip>
<input placeholder="Names"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event, asset)">
</mat-chip-list>
<mat-error>Atleast 1 name need to be added</mat-error>
</mat-form-field>
</form>
TS
import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {Component} from '@angular/core';
import {FormGroup, FormControl, FormBuilder, FormArray} from '@angular/forms';
import {MatChipInputEvent} from '@angular/material';
@Component({
selector: 'chip-list-validation-example',
templateUrl: 'chip-list-validation-example.html',
styleUrls: ['chip-list-validation-example.css'],
})
export class ChipListValidationExample {
public myForm: FormGroup;
// name chips
visible = true;
selectable = true;
removable = true;
addOnBlur = true;
readonly separatorKeysCodes: number[] = [ENTER, COMMA];
// data
data = {
names: ['name1', 'name2']
}
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
names: this.fb.array(this.data.names, this.validateArrayNotEmpty)
});
}
initName(name: string): FormControl {
return this.fb.control(name);
}
validateArrayNotEmpty(c: FormControl) {
if (c.value && c.value.length === 0) {
return {
validateArrayNotEmpty: { valid: false }
};
}
return null;
}
add(event: MatChipInputEvent, form: FormGroup): void {
const input = event.input;
const value = event.value;
// Add name
if ((value || '').trim()) {
const control = <FormArray>form.get('names');
control.push(this.initName(value.trim()));
console.log(control);
}
// Reset the input value
if (input) {
input.value = '';
}
}
remove(form, index) {
console.log(form);
form.get('names').removeAt(index);
}
}
问题是当 chipList 的 FormArray
状态为 INVALID
时,chipList 的 errorState
未设置为 true
。
我面临同样的问题,不知道为什么这不是开箱即用的,也不知道如何通过 chipList 的形式隐式实现 FormArray
.
作为解决方法,您可以从 FormArray
监听状态变化并手动设置 chipList 的 errorState
:
@ViewChild('chipList') chipList: MatChipList;
ngOnInit() {
this.myForm.get('names').statusChanges.subscribe(
status => this.chipList.errorState = status === 'INVALID'
);
}
遗憾的是,无法使用任何 Angular 的预定义验证器,因为它们并非设计用于数组。我在这篇文章的帮助下设法做到了:
https://www.dev6.com/Angular_Material_Chips_with_Reactive_Forms_and_Custom_Validation
为了能够在 mat-chip-list
上进行验证,我们必须将 mat-input
和 mat-chip-list
绑定为相同的 FormControl
,如下所示
工作 Stackblitz link here
<form [formGroup]='group'>
<mat-form-field class="example-chip-list">
<mat-chip-list #chipList
required
formControlName="newFruit">
<mat-chip *ngFor="let fruit of fruits"
(removed)="remove(fruit)">
{{fruit.name}}
<mat-icon matChipRemove>cancel</mat-icon>
</mat-chip>
<input placeholder="New fruit..."
formControlName="newFruit"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)" required>
</mat-chip-list>
<!-- add mat-error -->
<mat-error *ngIf="group.controls.newFruit.hasError('required')">required!</mat-error>
</mat-form-field>
</form>
正如 this example by mmalerba 所示,
您可以使用两个单独的表单控件:一个用于 mat-chip-list(这个应该是带有所需标志的那个),另一个用于输入。有趣的是,您必须在 addEvent:
上手动设置两者的值
<!-- ... -->
<mat-chip-list #chipList formControlName="names" required>
<!-- ... -->
<input placeholder="Names"
[formControlName]="name"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event, asset)">
</mat-chip-list>
<!-- ... -->
import {Validators} from '@angular/forms';
# ...
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
names: [this.data.names, Validators.required],
name: ['']
});
}
# ...
add(event: MatChipInputEvent, form: FormGroup): void {
const input = event.input;
const value = event.value;
// Add name
if ((value || '').trim()) {
const control = <FormArray>form.get('names');
control.push(this.initName(value.trim()));
console.log(control);
}
// Reset the input value
if (input) {
input.value = '';
}
// update form control (necessary for correct validation)
this.myForm.controls.name.setValue(null);
this.myForm.controls.names.setValue(this.data.names);
}
# ...
}
这是他们的 stackblitz example
因为有人正面临这个问题。几个小时后,我找到了问题的根本原因和解决方案:
在 chiplist 的添加、删除、select 函数中,您需要使用反应形式的函数 setValue 来使验证工作。
例如:
this.form.get('names').value.push('abc');
this.form.get('names').setValue(this.form.get('names').value); // => this line of code will make the validation work
如何验证 mat-chip
已添加到 mat-chip-list
。我正在使用 ReactiveForms。我已经尝试使用 required
验证器。
该值可以是一个姓名列表,因此在提交表单之前,我需要确保我的姓名列表中至少有 1 个姓名。如果列表为空,则 mat-error
应显示错误消息。使用 required
验证器会使表单无效,无论是否将名称添加到列表中。
编辑:反应形式
我已经尝试制作一个自定义验证器,我现在使用的是响应式表单而不是模板驱动的表单,但我无法让它工作。我编辑了以下代码以反映我的更改,并且我创建了这个 https://stackblitz.com/edit/angular-4d5vfj
HTML
<form [formGroup]="myForm">
<mat-form-field class="example-chip-list">
<mat-chip-list #chipList formArrayName="names">
<mat-chip *ngFor="let name of myForm.get('names').controls; let i=index;"
[formGroupName]="i"
[selectable]="selectable"
[removable]="removable"
(removed)="remove(myForm, i)">
<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
</mat-chip>
<input placeholder="Names"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event, asset)">
</mat-chip-list>
<mat-error>Atleast 1 name need to be added</mat-error>
</mat-form-field>
</form>
TS
import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {Component} from '@angular/core';
import {FormGroup, FormControl, FormBuilder, FormArray} from '@angular/forms';
import {MatChipInputEvent} from '@angular/material';
@Component({
selector: 'chip-list-validation-example',
templateUrl: 'chip-list-validation-example.html',
styleUrls: ['chip-list-validation-example.css'],
})
export class ChipListValidationExample {
public myForm: FormGroup;
// name chips
visible = true;
selectable = true;
removable = true;
addOnBlur = true;
readonly separatorKeysCodes: number[] = [ENTER, COMMA];
// data
data = {
names: ['name1', 'name2']
}
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
names: this.fb.array(this.data.names, this.validateArrayNotEmpty)
});
}
initName(name: string): FormControl {
return this.fb.control(name);
}
validateArrayNotEmpty(c: FormControl) {
if (c.value && c.value.length === 0) {
return {
validateArrayNotEmpty: { valid: false }
};
}
return null;
}
add(event: MatChipInputEvent, form: FormGroup): void {
const input = event.input;
const value = event.value;
// Add name
if ((value || '').trim()) {
const control = <FormArray>form.get('names');
control.push(this.initName(value.trim()));
console.log(control);
}
// Reset the input value
if (input) {
input.value = '';
}
}
remove(form, index) {
console.log(form);
form.get('names').removeAt(index);
}
}
问题是当 chipList 的 FormArray
状态为 INVALID
时,chipList 的 errorState
未设置为 true
。
我面临同样的问题,不知道为什么这不是开箱即用的,也不知道如何通过 chipList 的形式隐式实现 FormArray
.
作为解决方法,您可以从 FormArray
监听状态变化并手动设置 chipList 的 errorState
:
@ViewChild('chipList') chipList: MatChipList;
ngOnInit() {
this.myForm.get('names').statusChanges.subscribe(
status => this.chipList.errorState = status === 'INVALID'
);
}
遗憾的是,无法使用任何 Angular 的预定义验证器,因为它们并非设计用于数组。我在这篇文章的帮助下设法做到了:
https://www.dev6.com/Angular_Material_Chips_with_Reactive_Forms_and_Custom_Validation
为了能够在 mat-chip-list
上进行验证,我们必须将 mat-input
和 mat-chip-list
绑定为相同的 FormControl
,如下所示
工作 Stackblitz link here
<form [formGroup]='group'>
<mat-form-field class="example-chip-list">
<mat-chip-list #chipList
required
formControlName="newFruit">
<mat-chip *ngFor="let fruit of fruits"
(removed)="remove(fruit)">
{{fruit.name}}
<mat-icon matChipRemove>cancel</mat-icon>
</mat-chip>
<input placeholder="New fruit..."
formControlName="newFruit"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)" required>
</mat-chip-list>
<!-- add mat-error -->
<mat-error *ngIf="group.controls.newFruit.hasError('required')">required!</mat-error>
</mat-form-field>
</form>
正如 this example by mmalerba 所示, 您可以使用两个单独的表单控件:一个用于 mat-chip-list(这个应该是带有所需标志的那个),另一个用于输入。有趣的是,您必须在 addEvent:
上手动设置两者的值<!-- ... -->
<mat-chip-list #chipList formControlName="names" required>
<!-- ... -->
<input placeholder="Names"
[formControlName]="name"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event, asset)">
</mat-chip-list>
<!-- ... -->
import {Validators} from '@angular/forms';
# ...
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
names: [this.data.names, Validators.required],
name: ['']
});
}
# ...
add(event: MatChipInputEvent, form: FormGroup): void {
const input = event.input;
const value = event.value;
// Add name
if ((value || '').trim()) {
const control = <FormArray>form.get('names');
control.push(this.initName(value.trim()));
console.log(control);
}
// Reset the input value
if (input) {
input.value = '';
}
// update form control (necessary for correct validation)
this.myForm.controls.name.setValue(null);
this.myForm.controls.names.setValue(this.data.names);
}
# ...
}
这是他们的 stackblitz example
因为有人正面临这个问题。几个小时后,我找到了问题的根本原因和解决方案:
在 chiplist 的添加、删除、select 函数中,您需要使用反应形式的函数 setValue 来使验证工作。
例如:
this.form.get('names').value.push('abc');
this.form.get('names').setValue(this.form.get('names').value); // => this line of code will make the validation work