ilh*_*han 5 form-control angular-components angular angular5
我想在 Angular 5 中创建一个自定义选择输入控件。我有一个实现 SelectControlValueAccessor 的组件。当我实现如下所示的课程时。它在代码注释中给出了错误。
import { Component, Input, forwardRef, SimpleChanges, OnChanges } from '@angular/core';
import { SelectControlValueAccessor } from '@angular/forms';
import { SELECT_VALUE_ACCESSOR } from '@angular/forms/src/directives/select_control_value_accessor';
@Component({
selector: 'select-input',
template: ` `,
providers: [
{
provide: SELECT_VALUE_ACCESSOR,
useExisting: forwardRef(() => SelectInputComponent),
multi: true
}
]
})
/*
[ts]
Class 'SelectInputComponent' incorrectly implements class 'SelectControlValueAccessor'. Did you mean to extend 'SelectControlValueAccessor' and inherit its members as a subclass?
Property '_renderer' is missing in type 'SelectInputComponent'.
class SelectInputComponent
*/
export class SelectInputComponent implements SelectControlValueAccessor {
value: any; onChange: (_: any) => void;
onTouched: () => void;
compareWith: (o1: any, o2: any) => boolean;
writeValue(value: any): void {
throw new Error("Method not implemented.");
}
registerOnChange(fn: (value: any) => ): void {
throw new Error("Method not implemented.");
}
registerOnTouched(fn: () => ): void {
throw new Error("Method not implemented.");
}
setDisabledState(isDisabled: boolean): void {
throw new Error("Method not implemented.");
}
}
Run Code Online (Sandbox Code Playgroud)
我的配置如下: Typescript:2.5.3 Angular:5.2.11 VS Code:1.24.1
来自文档https://v6.angular.io/api/forms/SelectControlValueAccessor
SelectControlValueAccessor是指令而不是接口
import { Component, OnInit, Output, EventEmitter, Renderer2, ElementRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, SelectControlValueAccessor } from '@angular/forms';
@Component({
selector: 'select-input',
template: ` `,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => SelectInputComponent),
multi: true
}
]
})
export class SelectInputComponent extends SelectControlValueAccessor {
value: any;
onChange: (_: any) => void;
onTouched: () => void;
compareWith: (o1: any, o2: any) => boolean;
compareFn(c1: any, c2: any): boolean {
return c1 && c2 ? c1.key === c2.key : c1 === c2;
}
writeValue(value: any): void {
if (value) {
this.value.emit(value); }
}
registerOnChange(fn: (value: any) => any): void {
this.onChange = fn;
}
registerOnTouched(fn: () => any): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
throw new Error('Method not implemented.');
}
constructor(_renderer: Renderer2, _elementRef: ElementRef) {
super(_renderer, _elementRef);
}
}
Run Code Online (Sandbox Code Playgroud)
<select class="form-control" [compareWith]="compareFn" [(ngModel)]="value">
<option value="">Choose a option</option>
<option *ngFor="let option of options" [ngValue]="option">{{option.name}}</option>
</select>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4114 次 |
| 最近记录: |