有一个自定义输入组件,它以带有验证的反应形式使用:
@Component({
moduleId: module.id.toString(),
selector: 'custom-select',
templateUrl: 'custom-select.component.html',
styleUrls: ['custom-select.component.css']
})
export class CustomSelectComponent {
@Input() public items: SelectModel[];
public model: SelectModel;
constructor(private customSelectService: CustomSelectService) {
this.customSelectService.Selected.subscribe((data: SelectModel) => {
this.model = data;
});
}
public newSelect(select: SelectModel): void {
this.customSelectService.updateSelected(select);
}
}
效果很好,我正在使用custom-select
以反应形式并想要验证它,如下所示:
<custom-select id="country" [items]="selectItems" formControlName="country"></custom-select>
<div *ngIf=" myFrom.controls['country'].invalid && (myFrom.controls['country'].dirty
|| myFrom.controls['country'].touched) " class="ha-control-alert">
<div *ngIf="myFrom.controls['country'].hasError('required')">Country is required</div>
</div>
这就是我在组件中声明表单的方式
this.myFrom = this.formBuilder.group({
country: [null, Validators.required],
})
但是当我添加formControlName
对于验证,它会收到错误,表示没有用于名称为“country”的表单控件的值访问器。我应该如何处理这个问题?
STEPS
- 在装饰器中添加 NG_VALUE_ACCESSOR 的提供者
- 在类中实现 ControlValueAccessor
- 像这样创建 onChange 函数 onChange = (value: boolean) => {};
- 添加ControlValueAccessor接口的registerOnChange、writeValue和registerOnTouched方法
- 在要更改 select 值的方法中,调用 onChange 函数,并将 select 值作为参数传递。
import ...
import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
moduleId: module.id.toString(),
selector: 'custom-select',
templateUrl: 'custom-select.component.html',
styleUrls: ['custom-select.component.css'],
// STEP 1
providers: [{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => CustomSelectComponent)
}]
})
// STEP 2
export class CustomSelectComponent implements ControlValueAccessor {
// STEP 3
onChange = (value: SelectModel) => {};
@Input() public items: SelectModel[];
public model: SelectModel;
constructor(private customSelectService: CustomSelectService) {
this.customSelectService.Selected.subscribe((data: SelectModel) => {
this.model = data;
});
}
public newSelect(select: SelectModel): void {
// STEP 5
this.onChange(select);
this.customSelectService.updateSelected(select);
}
// STEP 4
registerOnChange(fn: (value: SelectModel) => void): void {
this.onChange = fn;
}
writeValue() {}
registerOnTouched(){}
}
不要忘记在选择器中添加 formControlName。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)