Par*_*kht 6 angular-validation angular angular-reactive-forms angular-forms
有一个自定义的输入组件,它以反应形式用于验证:
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
效果很好,我正在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>
Run Code Online (Sandbox Code Playgroud)
这就是我在组件中声明表格的方式
this.myFrom = this.formBuilder.group({
country: [null, Validators.required],
})
Run Code Online (Sandbox Code Playgroud)
但是当我添加formControlName验证时,会出现错误,提示名称为'country'的表单控件没有值访问器。我该如何处理?
小智 5
脚步
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(){}
}
Run Code Online (Sandbox Code Playgroud)
不要忘记在选择器中添加 formControlName。
| 归档时间: |
|
| 查看次数: |
5381 次 |
| 最近记录: |