【发布时间】:2019-08-04 21:41:12
【问题描述】:
我正在使用 Angular 6 做一个 Web 应用程序,并且我正在使用 Reactive Forms。我有一个带有数组的表单组,我在ngOnInit 中设置值。我有一个自定义验证器来了解名为 id 的字段是否是唯一的。
officesFormGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.officesFormGroup = this.fb.group({
offices: this.fb.array([], Validators.required)
});
}
ngOnInit() {
this.setOffices();
}
setOffices() {
const control = this.officesForm;
this.company.offices.forEach((office, index) => {
control.push(this.fb.group({
id: office.id,
name: office.name,
address: office.address,
services: this.fb.array([], Validators.required)
}, {validator: this.officeValidator.bind(this)}));
}
officeValidator(control: AbstractControl) {
const id = control.get('id').value;
if (id !== null && id !== '') {
const offices: Office[] = this.officesForm.value;
const isIdUnique = offices.map(office => office.id)
.some(value => value === id);
if (isIdUnique) {
control.get('id').setErrors({unavailable: true});
} else {
control.get('id').setErrors(null);
}
}
}
get officesForm() {
return this.officesFormGroup.get('offices') as FormArray;
}
将新办公室添加到阵列中:
addOffice() {
const office = this.fb.group({
id: [null, Validators.required],
name: [null, Validators.required],
address: [null, Validators.required],
services: this.fb.array([], Validators.required)
}, {validator: this.officeValidator.bind(this)});
this.officesForm.push(office);
}
ExpressionChangedAfterItHasBeenCheckedError:表达式已更改 检查后。以前的值:'ngIf: false'。当前值: 'ngIf: true'。
第一次加载页面时,id 字段显示为红色,好像有错误一样,这是错误的。如果用户添加另一个办公室并在id 字段中写入内容,它应该检查唯一性。
我的目标是,如果用户添加新办公室或尝试编辑现有办公室的id,请检查id 是否唯一,我的意思是,如果没有其他办公室具有相同的id。
【问题讨论】:
标签: angular