Bla*_*ord 5 typeahead ng-bootstrap
我正在使用ng-bootstrap typeahead组件来搜索客户数据库.当用户从预先输入结果列表中选择客户时,我会导航到客户详细信息页面.我有这个工作,但我想在导航发生后清除输入字段.我已经尝试将模型设置为null或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"/>
Run Code Online (Sandbox Code Playgroud)
客户搜索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
}
Run Code Online (Sandbox Code Playgroud)
选择完成后,预先输入如下所示:
解
客户搜索typeahead.component.html
<input type="text" class="form-control" #input [ngbTypeahead]="search" (selectItem)="onSelect($event); input.value='' ">
Run Code Online (Sandbox Code Playgroud)
客户搜索typeahead.component.ts
onSelect($event, input) {
$event.preventDefault();
this.router.navigate(['/customers', $event.item.resource.id]);
};
Run Code Online (Sandbox Code Playgroud)
pko*_*rce 22
您目击的问题源于NgModel指令异步更新模型绑定并在方法执行后更新实际模型onSelect.因此,您的模型更新会被NgModel功能覆盖.
幸运的是,我们(ng-bootstrap作者)获得了所有的灵活点来覆盖你的用例:-)你可以做几件事.
首先,$event传递给onSelect方法的对象具有该preventDefault()方法,您可以将其调用为否决项目选择(并因此写回模型和输入字段更新).
$event.preventDefault()将确保未更新模型,并且未使用所选项更新输入字段.但是用户输入的文本仍然是输入的一部分,所以如果你想要清除它,你也可以直接更新它input的value属性.
以下是一起展示所有这些技术的代码:
onSelect($event, input) {
$event.preventDefault();
this.selected.push($event.item);
input.value = '';
}
Run Code Online (Sandbox Code Playgroud)
其中inputargument是对输入DOM元素的引用:
<input type="text" class="form-control" #input
[ngbTypeahead]="search" (selectItem)="onSelect($event, input)">
Run Code Online (Sandbox Code Playgroud)
最后,这是一个在实践中显示所有这一切的人:http ://plnkr.co/edit/kD5AmZyYEhJO0QQISgbM?p=preview
| 归档时间: |
|
| 查看次数: |
8385 次 |
| 最近记录: |