我通过用自定义组件包装 ng-select 组件来解决这个问题。
@Component({
selector: 'ice-select',
templateUrl: './ice-select.component.html',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => IceSelectComponent),
multi: true
}
]
})
并在组件中实现了“ControlValueAccessor”的接口方法。
export class IceSelectComponent implements ControlValueAccessor, OnInit {
public writeValue(value: any) {
this.selectedValue = value;
}
public registerOnChange(fn) {
this.propagateChange = fn;
}
public registerOnTouched(fn){
this.propagateTouched = fn;
}
}
HTML模板,
<ng-select
[options]="options"
[multiple]="false"
[noFilter]="100"
[allowClear]="true"
[notFoundMsg]= "'No records found'"
placeholder="Select"
(selected)="onSelect($event)"
(deselected)="onRemove($event)"
[(ngModel)]="selectedValue"
></ng-select>