我已经使用表单构建器设置了一个表单,我想根据值更改设置自定义验证
所以这是我的表格
constructor(){
this.newtruck = this._formbuilder.group(
{
'trucktype':[''],
'transporter':[''],
'dropdown_transporter':[''],
'truck_number':[''],
'dropdown_truck_number':[''],
'driver_name':[''],
'dropdown_driver_name':[''],
'driver_number':[''],
'material':[''],
}
)
}
在下拉列表更改中,值将传递给此函数
updateSelectedValue(item) {
if(item){
if(item.dropdown == 1) {
this.newtruck.setControl("dropdown_transporter", new FormControl('', Validators.required));
this.newtruck.setControl("dropdown_transporter", new FormControl('', Validators.required));
this.newtruck.setControl("dropdown_driver_name", new FormControl('', Validators.required));
} else if(item.dropdown == 0){
this.newtruck.reset();
this.newtruck.setControl("transporter", new FormControl('', Validators.required));
this.newtruck.setControl("truck_number", new FormControl('', Validators.required));
this.newtruck.setControl("driver_name", new FormControl('', Validators.required));
this.newtruck.setControl("driver_number", new FormControl('', Validators.required));
}
}
}
现在在表格上我有一个按钮,我设置了
加密或禁用<button ion-button icon-rig color="danger" [disabled]="!newtruck.valid" (click)="onCreate()" > Save
<ion-icon name="send"></ion-icon>
</button>
上面的按钮总是被禁用,即使表单被实例化也可能是错误的,因为你可以看到最初没有调用验证器
答案 0 :(得分:1)
您可以通过自定义验证器函数包装验证器来将条件构建到验证器中。
this.newtruck.setControl("dropdown_transporter",
new FormControl('',
(control:Control) => {
if(item && item.dropdown == 1) {
return Validators.required(control)
}
)
);
你也可以移出整个功能,如
updateSelectedValue(item)
var requiredValidator = (control:Control) => {
if(item && item.dropdown == 1) {
return Validators.required(control)));
}
};
this.newtruck.setControl("dropdown_transporter",
new FormControl('', requiredValidator));
...
}