我使用ng-bootstrap typeahead組件來搜索客戶數據庫。當用戶從預先結果列表中選擇一個客戶時,我會導航到客戶詳細信息頁面。我有這個工作,但我想在導航發生後清除輸入字段。我試過設置模式爲空或selectItem
事件邏輯空字符串,但是這是行不通的:如何在選擇結果後清除鍵入輸入?
客戶搜索typeahead.component.html
<template #resultTemplate let-r="result" let-t="term">
<div>
<div>
{{r.resource.name[0].given}} {{r.resource.name[0].family}}
</div>
<div>
{{r.resource.birthDate | date: 'dd/MM/yyyy'}}
</div>
</div>
</template>
<input type="text" class="form-control" [resultTemplate]="resultTemplate" (selectItem)="onSelect($event)"
[(ngModel)]="model" placeholder="Start typing a customer name..." [ngbTypeahead]="search"/>
客戶 - 搜索 - typeahead.component.ts
@Component({
selector: 'customer-search-typeahead',
template: require('./customer-search-typeahead.component.html'),
styles: [`.form-control { width: 300px; }`]
})
export class CustomerSearchTypeaheadComponent {
model: any;
searching: boolean;
constructor(private customerService: CustomerService, private router: Router) {}
onSelect($event) {
this.router.navigate(['/customers', $event.item.resource.id]);
this.model = null;
};
search = (text$: Observable<string>) =>
//omitted for brevity
}
選擇後的預輸入輸入看起來像這樣已經取得:
解決方案
客戶搜索typeahead.component.html
<input type="text" class="form-control" #input [ngbTypeahead]="search" (selectItem)="onSelect($event); input.value='' ">
客戶搜索typeahead.component.ts
onSelect($event, input) {
$event.preventDefault();
this.router.navigate(['/customers', $event.item.resource.id]);
};
我剛剛注意到,這適用於第一次搜索和輸入框被清除,但隨後的搜索結果在se拱字符串保留在輸入字段中。我已經嘗試了你所建議的所有組合。 –
@BlakeMumford我明白了!我已根據您的使用案例和評論更新了我的答案。希望它現在能夠滿足您的需求。 –
嗨,那效果很好,但我的組件正在執行DOM操作。我已經用我最終使用的解決方案更新了我的問題。謝謝你的幫助! –