2016-09-30 49 views
0

我使用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 
} 

選擇後的預輸入輸入看起來像這樣已經取得:

enter image description here


解決方案

客戶搜索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]); 
    }; 

回答

8

的問題,您看到的事實產生了NgModel指令更新模型異步約束力和實際模型更新onSelect方法被執行。因此,您的型號更新將被NgModel功能覆蓋。

幸運的是,我們(ng-bootstrap的作者)得到了所有的彈性點來覆蓋你的用例:-)有幾件事你可以做。

首先傳遞給onSelect方法$event對象具有preventDefault()方法,你可以把它否決項目選擇(並因此寫回模型和輸入字段更新)。

$event.preventDefault()將確保模型沒有更新,並且輸入字段沒有被選中的項目更新。但用戶輸入的文本仍然是輸入的一部分,因此如果您想要清除此內容,則可以直接更新inputvalue屬性。

下面是代碼演示所有這些技術一起:

onSelect($event, input) { 
    $event.preventDefault(); 
    this.selected.push($event.item); 
    input.value = ''; 
    } 

其中input參數是所述輸入DOM元素的引用:

<input type="text" class="form-control" #input 
    [ngbTypeahead]="search" (selectItem)="onSelect($event, input)"> 

最後這裏是示出在實踐中,這全部plunker: http://plnkr.co/edit/kD5AmZyYEhJO0QQISgbM?p=preview

+0

我剛剛注意到,這適用於第一次搜索和輸入框被清除,但隨後的搜索結果在se拱字符串保留在輸入字段中。我已經嘗試了你所建議的所有組合。 –

+0

@BlakeMumford我明白了!我已根據您的使用案例和評論更新了我的答案。希望它現在能夠滿足您的需求。 –

+0

嗨,那效果很好,但我的組件正在執行DOM操作。我已經用我最終使用的解決方案更新了我的問題。謝謝你的幫助! –

相關問題