Angular 表达式在使用反应形式检入角度后发生了更改
我在Angular 6中做一个web应用程序,我使用的是反应式表单。我有一个带有数组的表单组,我正在设置ngOnInit中的值。我有一个自定义验证器来知道名为id的字段是否唯一Angular 表达式在使用反应形式检入角度后发生了更改,angular,Angular,我在Angular 6中做一个web应用程序,我使用的是反应式表单。我有一个带有数组的表单组,我正在设置ngOnInit中的值。我有一个自定义验证器来知道名为id的字段是否唯一 officesFormGroup: FormGroup; constructor(private fb: FormBuilder) { this.officesFormGroup = this.fb.group({ offices: this.fb.array([], Validators.requ
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);
}
ExpressionChangedTerithasBeenCheckedError:表达式已更改
检查过之后。上一个值:“ngIf:false”。当前值:
“ngIf:对”
第一次加载页面时,名为id的字段显示为红色,就像它有错误一样,这是错误的。如果用户添加了另一个office并在id字段中写入了内容,则应检查unique
我的目标是,如果用户添加一个新办公室或试图编辑一个现有办公室的id,请检查该id是否唯一,我的意思是,如果没有其他办公室具有相同的id。我在应用程序中使用了@rxweb/reactive form validators的唯一验证器,通过在我的formControl实例中使用RxwebValidators.unique来检查id是否唯一,因为在某种程度上,我面临着同样的问题 我已经在Id属性上应用了唯一验证程序。请参阅下面的代码 组件1.ts:
export class UniqueValidatorComponent implements OnInit {
officesFormGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.officesFormGroup = this.fb.group({
offices: this.fb.array([])
});
}
ngOnInit() {
this.addOffice();
}
addOffice() {
const office = this.fb.group({
id: [null,[ Validators.required,RxwebValidators.unique()]],
name: [null, Validators.required],
address: [null, Validators.required],
services: this.fb.array([], Validators.required,)
});
this.officesForm.push(office);
}
get officesForm() {
return this.officesFormGroup.get('offices') as FormArray;
}
}
请参考此示例:
请参阅与唯一验证相关的内容RxwebValidators将检查您添加的id是否已存在于阵列中的另一个office中,对吗?怎样我不明白RxwebValidators在哪里或如何比较所有id。@RRGT19一旦您在相应列上安装了唯一验证器,唯一验证器将使用该列的其他行验证值。您可以参考本文: