我有一个要在表上添加的表单字段值。我需要显示两个验证。需要一个正在工作的。另一个是自定义验证(已添加到表中)。 当值已经存在于表中的数组数据中时,我创建了一个布尔值,它为true。 如何实现第二个自定义验证?这是我到目前为止尝试过的,但是没有用。有没有更简单的方法呢?谢谢
HTML
<mat-form-field >
<mat-select formControlName="serviceName" placeholder="Service Type" (selectionChange)="onServiceSelectionChanged($event)">
<mat-option *ngFor="let service of allServicesFromDB" [value]="service.id">
{{service.name}}
</mat-option>
</mat-select>
<mat-error>{{getServiceErrorMessage()}}</mat-error>
</mat-form-field>
TS
createFormServices() {
this.servicesFormGroup = this.fb.group({
id: [0],
serviceName: ['',Validators.required],
trackingMethod: ['',Validators.required],
qtyTotal: ['',Validators.required],
});
}
仅在单击按钮addToTable时触发错误
addToTable() {
const serviceControls = this.servicesFormGroup.controls;
//should trigger error when true
this.serviceAlreadyAdded = this.servicesTableData.some(x => x.serviceId === this.servicesFormGroup.value.serviceName);
if(this.servicesFormGroup.invalid) {
Object.keys(serviceControls).forEach(controlName =>
serviceControls[controlName].markAsTouched());
this.getServiceErrorMessage()
return;
}
else if(this.serviceAlreadyAdded) {
Object.keys(serviceControls).forEach(controlName =>
serviceControls[controlName].markAsTouched());
this.getServiceErrorMessage()
return;
}
else {
//populate table
}
我的功能
getServiceErrorMessage() {
var x = this.servicesFormGroup.controls['serviceName'].hasError('required') ? 'Service is required' :
this.serviceAlreadyAdded ? 'Service already added' :
'';
return x
}