我正在关注Angular 2上的一些教程,并尝试将一个简单的Typeahead组件组合在一起。它正在工作,但是我想添加一个选项,在键入最小长度的字符串之前,不要点击服务器。我可以通过在流中添加一个过滤器来做到这一点(但是),但是当我退格到最小值以下(或从输入中删除文本)时,我希望提前输入清除。目前,如果我输入最小长度和退格键,结果将保持不变。
我可以向其中添加* ngIf并进行表单验证,table但是这种感觉很不客气,我认为我应该能够以某种方式将空数组发送到模板。但是我找不到任何有效的方法。
这是我所拥有的精简版:
@Component({
selector: 'typeahead',
template: `
<div>
<input
required
type="text"
placeholder="Person"
#person [ngFormControl]="searchText">
</div>
<table>
<tbody>
<tr *ngFor="#person of people | async">
<td> {{person.name}}</td>
</tr>
</tbody>
</table>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TypeAhead {
searchText = new Control();
people: Observable<any[]>;
constructor(db:DBService){
this.people = this.searchText.valueChanges
.debounceTime(200)
.filter((val:string) => (val.length > 1))
.switchMap((val:string) => db.searchNodes("Person", val))
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个干净的工作解决方案,基于:
使用可观察对象时如何防止在Angular 2中进行http调用?
constructor(db:DBService){
this.people = this.searchText.valueChanges
.debounceTime(200)
.switchMap((val:string) => val.length > 1
? db.searchNodes("Person", val))
: Observable.of([]))
}
Run Code Online (Sandbox Code Playgroud)
为了使用,Observable.of您需要导入import 'rxjs/Rx';
| 归档时间: |
|
| 查看次数: |
3702 次 |
| 最近记录: |