我正在研究mat-chip-list,其中声明了要输入的formArray控件。
当前行为: 当我只提交表单而没有填写任何表单字段时,mat-chip-list里面没有任何formcontrols,但是当我打印formGroup时,required:true验证显示,但是mat-chio-list框的红色边框没有显示显示。
预期行为: 表单验证必须显示带有红色边框的mat-chip-list
我的Component.ts:
this.composeMailForm = new FormGroup({
to_emails: new FormArray([], Validators.required),
cc_emails: new FormControl(),
bcc_emails: new FormControl(),
from_email: new FormControl(),
subject: new FormControl('', Validators.required),
body: new FormControl('', Validators.required),
});
onSubmit(){
console.log("form controls after submit",this.composeMailForm);
if(this.composeMailForm.valid){
------------
------------
}else{
this.composeMailForm.controls.body.markAsTouched();
const ctrls = this.composeMailForm.get('to_emails') as FormArray;
ctrls.markAsTouched();
ctrls.controls.forEach(control => control.markAsTouched());
this.composeMailForm.controls.subject.markAsTouched();
}
add(event: MatChipInputEvent, email_type): void {
const input = event.input;
const value = event.value;
if ((value || '').trim()) {
if(email_type === 'to_email'){
const to_emails = this.composeMailForm.get('to_emails') as FormArray;
to_emails.push(this.fb.control(value.trim()));
}
}
}
remove(index: number, email_type): void {
if(email_type === 'to_email'){
const to_emails = this.composeMailForm.get('to_emails') as FormArray;
if (index >= 0) {
to_emails.removeAt(index);
}
}
}
HTML:
<mat-label>To</mat-label>
<mat-chip-list #chipList ngDefaultControl formArrayName="to_emails" >
<mat-chip *ngFor="let email of composeMailForm.get('to_emails').controls; let i = index;" [selectable]="selectable" [removable]="removable"
(removed)="remove(i,'to_email')" ngDefaultControl >
{{email.value}}
<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
</mat-chip>
<input [matChipInputFor]="chipList" [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur" (matChipInputTokenEnd)="add($event,'to_email')" >
</mat-chip-list>
如何实现这一目标,任何想法?谢谢。