嗨,我是2/4的新用户。我需要在显示结果的同时突出显示要搜索的单词(搜索到的关键字在搜索结果中将以粗体显示)。在搜索过程中,将显示“按您输入”的建议。就像这个Google image here。
这是我的Component.ts
DetailsSearch(itemcode: string): void {
this.searchflag = 1;
this.pageIndex = 1;
this.prevScrollPosition = 0;
if (itemcode.length > 0) {
this.searchcontent = itemcode;
}
else {
itemcode = undefined;
this.searchcontent = itemcode;
}
this._Service.DetailsSearch(this.searchcontent, this.pageIndex).subscribe(itemsData => this.itemdetails = itemsData,
error => {
console.error(error);
this.statusMessage = "Problem with the service.Please try again after sometime";
});
}
这是我的html
<form role="form">
<div class="row">
<div class="form-group">
<div class="input-group">
<input class="form-control" type="text" name="search" placeholder="Search" required="" [(ngModel)]='searchcontent'>
<span class="input-group-btn">
<button class="btn btn-danger ProductSearchBtn" type="button" (click)='DetailsSearch(searchcontent)'><i class="glyphicon glyphicon-search" aria-hidden="true"></i><span style="margin-;">Search</span></button>
</span>
</div>
</div>
</div>
</form>
答案 0 :(得分:1)
您可以使用Angular Material Autocomplete组件轻松完成此操作:https://material.angular.io/components/autocomplete/examples
那里的例子可以帮助您入门。
然后突出显示要搜索的文本,可以在显示文本的跨度中使用管道。如果以“材料自动完成”为例,它看起来像这样:
<mat-option *ngFor="let state of filteredStates | async" [value]="state.name">
<span [innerHTML]="state.name | highlightSearch:stateCtrl.value"></span>
</mat-option>
使用管道:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'highlightSearch'
})
export class HighlightSearchPipe implements PipeTransform {
transform(value: string, search: string): string {
return value.replace(new RegExp('(?![^&;]+;)(?!<[^<>]*)(' + search + ')(?![^<>]*>)(?![^&;]+;)', 'gi'), '<strong class="your-class">$1</strong>');
}
}
管道将以粗体显示键入的文本,并应用“您的类”中的所有CSS。
我确定那里有更好的解决方案。这对我有用。 希望这会有所帮助!
答案 1 :(得分:0)
如果要创建有角度的预先输入搜索,请尝试使用反应形式
<form class="form-inline">
<div class="form-group">
<input type="search"
class="form-control"
(keypup)="doSearch"
placeholder="Enter search string"
[formControl]="searchField">
</div>
</form>
检查以下博客 https://codecraft.tv/courses/angular/http/http-with-observables/