我创建了一个searchable-dropdown
组件,我需要在许多组件中使用它,现在我在将表单绑定(bind)到该组件时遇到问题。
例如,我有一个用于创建用户的 from,我需要将一个字段的验证绑定(bind)到 searchable-dropdown
组件。
private createForm(): void {
this.courseAddForm = this.formBuilder.group({
name: ['', [
Validators.required,
Validators.maxLength(this.val.maxLen.title)
]],
roleId: ['', Validators.compose([Validators.required])]
});
}
我需要在此组件中绑定(bind)roleId
验证:
<div class="col-lg-6 kt-margin-bottom-20-mobile">
<kt-searchable-dropdown [formGroup]="courseAddForm" [formcontrolName]="'roleId'"
(selectedId)="selectedCourse($event)" [formTitle]="'COURSE.COURSE_GROUP'">
</kt-searchable-dropdown>
</div>
我尝试使用此代码来查找此表单的 roleId
的 vlaidation,但它对我不起作用:
@Input() url: string;
@Input() formTitle: string;
@Input() ItemId: number;
@Input() formcontrolName: string;
@Input() formGroup: FormGroup;
@Input() control: FormControl;
@Output() selectedId = new EventEmitter<number>();
fieldErrors(field: string): any {
let controlState = this.formGroup.controls[field];
return (controlState.dirty || controlState.touched) ? controlState.errors : null;
}
HTML:
<div class="col-lg-12 mt-4 kt-margin-bottom-20-mobile">
<mat-form-field class="mat-form-field-fluid" appearance="outline">
<mat-label>{{'GENERAL.TITLE' | translate}} *</mat-label>
<input [formControlName]="formcontrolName" (keyup)="getValues($event.target.value)" matInput
[placeholder]="'GENERAL.TITLE' | translate">
<span *ngIf="fieldErrors(formcontrolName)" class="text-right">
<label *ngIf="fieldErrors(formcontrolName).required">WORKED</label>
</span>
</mat-form-field>
</div>
我该如何解决这个问题???
最佳答案
您需要在此可搜索下拉组件中实现 CustomValueAccessor。
例如,可以在响应式(Reactive)表单上使用的自定义文件组件:
@Component({
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: FileUploadComponent,
multi: true
}
]
})
export class FileUploadComponent implements ControlValueAccessor {
@Input() progress;
onChange: Function;
private file: File | null = null;
@HostListener('change', ['$event.target.files']) emitFiles( event: FileList ) {
const file = event && event.item(0);
this.onChange(file);
this.file = file;
}
constructor( private host: ElementRef<HTMLInputElement> ) {
}
writeValue( value: null ) {
// clear file input
this.host.nativeElement.value = '';
this.file = null;
}
registerOnChange( fn: Function ) {
this.onChange = fn;
}
registerOnTouched( fn: Function ) {
}
}
Here is a detailed blog post关于您需要做什么。
关于javascript - 将表单验证绑定(bind)到当前组件之外的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59341707/