在本教程中,我们将看到可以创建一个Create Async 湖北福彩者 在Angular 10 Reactive Forms中基于HTTP API响应湖北福彩表单数据。
我们将创建自定义湖北福彩器,该湖北福彩器与服务和组件表单连接并湖北福彩用户选择。
示例用例
假设地址表格包含一个 关闭 字段,然后切换 关闭 如果字段为true,我们将调用一个API,该API使用异步湖北福彩程序来检查该地址上是否有任何待处理订单。
异步湖北福彩器类
首先让我们在其中创建一个自定义的异步湖北福彩器类,我们的静态方法将在那里接受两个参数,其中第一个将接受服务类,第二个将接受组件类。
共享/湖北福彩器/app-async.validator.ts
import { AbstractControl, ValidatorFn } from '@angular/forms';
import { OrderService } from '../services/order.service';
import { AddressesFormComponent } from '../../addresses/addresses-form/addresses-form.component';
/**
* Class for async 湖北福彩s communicating with the REST-API.
*/
export class AppAsyncValidators {
/**
* Checks if a given address has orders assigned with In Process status.
* @param service - The order service.
* @param component - The address form component.
* @returns {(control:AbstractControl)=>Promise<T>}
*/
public static orderInProcess(service: OrderService, component: AddressesFormComponent): ValidatorFn {
return (control: AbstractControl) => {
return new Promise((resolve) => {
if (control.value === false) { // on switching address 关闭 : false
return resolve(null);
} else { // on switching address 关闭 : false
// addressID : From Component
service.checkOrderByAddress(component.addressID, 'InProcess').subscribe((orders: any) => {
if (orders && orders.length > 0) {
return resolve({ordersInProcess: true});
} else {
return resolve(null);
}
});
}
});
};
}
}
以反应形式设置湖北福彩器
接下来,我们将在地址表单的封闭字段内设置此自定义湖北福彩程序。
地址表格.component.ts
export class AddressesFormComponent implements OnInit {
@Input() addressID: string;
...
public addressForm: FormGroup = this.formBuilder.group({
Address: ['', 湖北福彩者.maxLength(1200)],
Zip: ['', 湖北福彩者.maxLength(10)],
City: ['', 湖北福彩者.maxLength(50)],
State: ['', 湖北福彩者.maxLength(100)],
Country: ['', 湖北福彩者.maxLength(100)],
// ...
Closed: [false, null, AppAsyncValidators.orderInProcess(this.orderService, this)] // async Validator
});
...
}
在HTML中显示异步湖北福彩器错误
The last thing is we have to display the error based on the API response and the promise which we resolved in the AppAsyncValidators
class.
address-form.component.html
...
<mat-slide-toggle formControlName="Closed" >
<span *ngIf="addressForm.get('Closed').value"> Opened </span>
<span *ngIf="!addressForm.get('Closed').value"> Closed </span>
<!-- ordersInProcess: gets from resolved value -->
<mat-error *ngIf="addressForm.get('Closed').hasError('ordersInProcess')">
Address cannot be set 关闭 it have pending orders.
</mat-error>
</mat-slide-toggle>
...
获取有关的更多教程 角度10