搜索组件
首页顶部的搜索框要开始实现了。使用场景很明确,就是去根据关键字去调用专用的接口拿到返回值后渲染到组件中。
为了方便维护,将搜索框封装成单独的模块
创建search模块
// 在wy-ui下执行
ng g m wy-search
ng g c wy-search
为了避免循环引用shareModule,所以要在WySearchModule中逐个引用。
自定义组件
使用ng-container和ng-template标签灵活创建组件渲染的内容
- wy-search.component.html
<ng-template #default>
<div class="search" #search>
<nz-input-group nzSuffixIcon="search">
<input nz-input #nzInput placeholder="歌单/歌手" />
</nz-input-group>
</div>
</ng-template>
<ng-container *ngTemplateOutlet="default"></ng-container>
- app.component.html
<app-wy-search (onSearch)="onSearch($event)"></app-wy-search>
- wy-search.component.ts
@ViewChild('nzInput', {
static: false }) private nzInput: ElementRef;
@Output() onSearch = new EventEmitter<string>();
// 发射输入框的值
ngAfterViewInit (): void {
fromEvent(this.nzInput.nativeElement, 'input')
.pipe(
debounceTime(300), // 防抖
distinctUntilChanged(), // 去重
pluck('target', 'value')
).subscribe((input: string) => {
this.onSearch.emit(input);
})
}
当试图渲染完成之后就去绑定输入框,将每次的输入值经过防抖和去重后发射给父组件。
这里的自定义体现在app模块可以自己定义一个templateref类型的内容,然后通过引用类型将值传给子组件。
调用接口
- search.service.ts
// 获取关键字搜索内容
search (keywords: string): Observable<SearchResult> {
const params = new HttpParams().set('keywords', keywords);
return this.http.get(this.uri + 'search/suggest', {
params }).pipe