【发布时间】:2022-11-05 21:33:47
【问题描述】:
嗨,我正在做一个Angular 12 应用程序使用材料.
我有这样的 FormGroup
form:FormGroup=new FormGroup({
Id: new FormControl(null),
Name: new FormControl('',Validators.required),
Recipents: new FormControl('',[Validators.required, matchingEmailValidator()]),
IsActive: new FormControl(true),
ProcessorName: new FormControl('',Validators.required),
Channel: new FormArray([],[ matchingCheckValidator()]),
});
我有一个从数据库动态加载的复选框数组。
我想放一个自定义验证器验证是否至少选择了一个复选框。如果没有,请使用
<mat-error>This field is mandatory</mat-error>
我还有一个名为channelList 的变量,我的所有复选框都已选中。
changeEventFunc( ob: MatCheckboxChange) {
if (ob.checked) {
this.channelList.push(ob.source.id);
} else {
this.channelList.forEach((element,index)=>{
if(element== ob.source.id)
{
this.channelList.splice(index, 1);
}
}
)}
}
我定义了一个函数调用匹配检查验证器我想把验证放在哪里
export function matchingCheckValidator(): ValidatorFn {
return (control:AbstractControl) : ValidationErrors | null => {
do the task
}
}
}
这是我的 HTML
<mat-label><strong>Channel</strong></mat-label>
<li *ngFor="let chanel of notification.NotificationChannelLogLevels">
<mat-checkbox id= {{chanel.NotificationLogLevel.Id}} formArrayName="Channel"
[checked]="chanel.IsActive"
(change)="changeEventFunc($event)">
{{chanel.NotificationLogLevel.Name}}
</mat-checkbox>
</li>
每次选中复选框时,我都需要运行自定义验证...
那可能吗?
谢谢
【问题讨论】:
标签: validation angular-material formgroups angular-validator