找到解决方案
模板和组件的控制器示例。请阅读代码中的注释。
模板:
<ng-select #select (change)="onChange($event)" ... >
...
</ng-select>
通常,我们需要对组件和change
事件处理程序的引用。
控制器:
@Component(...)
export class NgSelectWrapper implements OnInit, OnChanges
@Input() value: string | number;
@Output() changed = new EventEmitter<string>();
private _selectedValue: string | number;
ngOnChanges(changes: SimpleChanges): void {
if (changes.value) {
// Selected value can be changed only through the @Input field.
this._selectedValue = changes.value.currentValue;
// First time itemsList of ng-select component is not initialized,
// so we need to wait to the next tick to select an item.
setTimeout(() => this.selectValue(this._selectedValue), 0);
}
}
onChange(event: NewDropdownOptionModel) {
// Overwrite selection done by the user interaction and select the previous item forcibly.
// So only ngOnChanges hook can change the selected item.
this.selectValue(this._selectedValue);
if (event.id !== this._selectedValue) {
this.changed.emit(event.id);
}
}
private selectValue(value: string | number): void {
if (value) {
if (!this.trySelectItem(value)) {
this.select.clearModel();
}
}
}
private trySelectItem(value: string | number): boolean {
const item = this.select.itemsList.findItem(value);
return item
? (this.select.select(item), true)
: false;
}
}
所以我们不需要使用[(ngModel)]
绑定和手动处理一个项目的选择。