该页面使用了Typehead
组件。
该组件中显示了一个数据数组:
[{id: 1, address: 'cat'}, {id: 2, address: 'dog'}]
列表中的数据按预期显示,但是如果单击列表项,则[object Object]显示在input中:

如何显示列表中选择的对象的地址?
但是,不要使用ng-template,因为我认为对于这样一个简单的任务来说它是多余的。
组件配置如下:
HTML:
<input
id="typeahead-focus"
type="text"
class="form-control"
[(ngModel)]="model"
[ngbTypeahead]="search"
(focus)="focus$.next($event.target.value)"
(click)="click$.next($event.target.value)"
[resultFormatter]="formatter"
#instance="ngbTypeahead"
/>
TS:
@Component({
selector: 'ct-typeahead',
templateUrl: './typeahead.component.html',
styleUrls: ['./typeahead.component.sass']
})
export class TypeaheadComponent implements OnInit {
model: any;
values: any[];
formatter = (result: any) => result.address;
constructor() {
this.values = [{id: 1, address: 'cat'}, {id: 2, address: 'dog'}]
}
ngOnInit() { }
@ViewChild('instance') instance: NgbTypeahead;
focus$ = new Subject<string>();
click$ = new Subject<string>();
search = (text$: Observable<string>) => {
const debouncedText$ = text$.pipe(debounceTime(200), distinctUntilChanged());
const clicksWithClosedPopup$ = this.click$.pipe(filter(() => !this.instance.isPopupOpen()));
const inputFocus$ = this.focus$;
return merge(debouncedText$, inputFocus$, clicksWithClosedPopup$).pipe(
map(term => (term === '' ? this.values
: this.values.filter(v => v.address.toLowerCase().indexOf(term.toLowerCase()) > -1)))
);
};
}
首先,我有一个问题,
searchString函数内部的变量来自哪里indexOf,但没关系。其次
ngModel,它很棒,但input它不了解对象是什么并将对象转换为字符串({}).toString() => [object Object]。如果将以下 getter 添加到组件中:并使用属性绑定
input:model单击按钮后将成为一个对象dropdown-item,而在此之前,model当您在 中键入内容时它是一个字符串input。或者您可以使用绑定
inputFormatter。如果fomatter用于格式化搜索结果,则inputFormatter用于格式化所选值并将其显示在input.