Выделение результатов поиска в angular - PullRequest
0 голосов
/ 20 марта 2020

У меня есть поисковая система, где люди могут выполнять поиск по своим терминам, и результат чувствителен к регистру, а также ищет содержащийся термин в полях.

Я хотел бы выделить термин, который ищет пользователь в результат (html), чтобы ему было легче найти результат.

Это мой файл ts:

export class HomeComponent implements OnInit {
drugSearch = 'http://localhost:8080/drugs/search?q=';
searchResults: any;
loading: boolean;
searchTerm = new Subject<string>();
drugsList: Observable<PaginatedSearchResponse<Drug>>;
emptyObservable = false;

constructor(private http: HttpClient, private drugService: DrugsService, private router: Router, 
private cardService: CardService) {
this.searchTerm.pipe(
  map((e: any) => e.target.value),
  debounceTime(700),
  distinctUntilChanged(),
  filter(term => term.length >= 1)
).subscribe(searchTerm => {
  this.loading = true;
  this._searchEntries(searchTerm);
});
}

ngOnInit() {
this.fetchDrugs();

if (this.cardService.drugs.length != 0) {
  this.emptyObservable = true;
}

}

searchEntries(term: any): Observable<any> {
return this.http.get(this.drugSearch + term).pipe(
  map(response => {
    this.searchResults = response;
    //  console.log(response);
  })
)
}

_searchEntries(term: any) {
this.searchEntries(term).subscribe(response => {
  this.loading = false;
}, err => {
  this.loading = false;
})
}

А это мой html файл

<div class="container myPadding">
<div class="form-row justify-content-center">
    <h1>Search Engine</h1>
</div>

<div class="form-row justify-content-center">
    <div class="form-group col-md-7">
        <input autofocus type="text" placeholder="Search a Drug. Example: Depon" class="form-control text-center"
            (keyup)="searchTerm.next($event)">
        <div *ngIf="loading" class="alert alert-danger text-center mt-5">Searching...</div>
    </div>
</div>

<div class="form-row justify-content-center">
    <p class="alert alert-info">
        Total Drugs registered: ({{ (drugsList | async)?.totalElements }})
    </p>
</div>

<div class="form-row justify-content-center">
    <button *ngIf="emptyObservable" (click)="goToCard()" class="alert alert-warning btn btn-warning">Shopping Card
        ({{ (this.cardService.getDrugs() | async)?.length }})</button>
</div>

<a *ngIf="searchResults">
    <table class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr>
                <th>Slot</th>
                <th>Drug Name</th>
                <th>Substances</th>
                <th>Type</th>
                <th>Expire</th>
                <th>Entry Date</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody *ngFor="let result of searchResults.content | slice:0:99">
            <tr>
                <td>{{result.slot.number}}</td>
                <td>{{result.tradingName}}</td>
                <td>
                    <p *ngFor="let subs of result.substances">{{subs.dose}}{{subs.entity}},
                        {{subs.substance.substanceName}}</p>
                </td>
                <td>{{result.type}}, {{result.quantity}}</td>
                <td>{{birthdayToString(result.expire)}}</td>
                <td>{{result.entryDate}}</td>
                <td><button (click)="addToCard(result)" class="btn btn-success ml-1">Add</button></td>
            </tr>
        </tbody>
    </table>
</a>

Под выделением я подразумеваю добавление некоторого стиля к термину, который ищет пользователь, или даже лучше к тд, где содержится его термин. Должен ли я решить это с помощью регулярных выражений? И если да, то как?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...