表單初始數據:
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 } }) }