表单初始数据:
this.deviceForm = this.fb.group({ name: ["", [Validators.required]], serialNumber: [""], modelname: [""], // 设备型号 model: [""], // 型号 modelId: ["", [Validators.required]], //模型ID make: [""], // 生成厂家 model_memo: [""], // 备注 iconType: ["", [Validators.required]], //类型 mode: "", modename: "", subnet: ["", [this.validateSubnet]], devicePorts: this.fb.array([this.creatPort()])
表单联动改变:modelId 改变时,为make.和model_memo 赋值。当modelId为 -1时,新建model.
formModelChangeEmit() { this.deviceForm.get("modelId").valueChanges.subscribe((value) => { if (value == -1) { this.modeShowChange(true) } else { let model = this.device.models.find((item) => item.modelId == value) if (model) { this.deviceForm.patchValue({ make: model.make, model_memo: model.model_memo }) } } }) }
modeShowChange(show) {
this.device.modeShow = show
if (show) {
this.deviceForm.patchValue({
make: "",
model_memo: ""
})
} else {
this.deviceForm.patchValue({
modelId: this.device.models[1].modelId
})
}
}
表单IconType改变时,修改表单的control;这里使用removeControl和addControl 主要是为了解决from的valid状态问题。
formIcontypeChangeEmit() { this.deviceForm.get("iconType").valueChanges.subscribe((value) => { if (value == "subnet") { this.deviceForm.removeControl("modelId") this.deviceForm.removeControl("devicePorts") this.deviceForm.updateValueAndValidity() this.deviceForm .get("subnet") .setValidators([Validators.required, this.validateSubnet]) this.subnetShow = true } else { this.deviceForm.get("subnet").setValidators(null) this.deviceForm.addControl( "modelId", new FormControl("", [Validators.required]) ) this.deviceForm.addControl( "devicePorts", this.fb.array([this.creatPort()]) ) this.formModelChangeEmit() this.subnetShow = false } }) }