我有一個搜索欄,在輸入文本時顯示結果,問題是:
- 即使輸入欄位/搜索欄為空,搜索結果也不會消失。
- 如果我按 ESC 或在搜索欄或搜索結果之外單擊,它不會關閉。我用渲染器和主機視圖嘗試了不同的東西,我不能讓它作業。如果是普通的js,我敢肯定我會解決這個問題的。Angular 有太多特殊的怪癖,我需要一些幫助。
這就是問題的樣子:問題
components.ts 檔案(洗掉了我失敗的嘗試):
import {
Component,
OnInit,
Renderer2,
ElementRef,
ViewChild,
} from '@angular/core';
import { faSearch } from '@fortawesome/free-solid-svg-icons';
import { CountryService } from '../services/country.service';
import { OneCountry } from '../country';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css'],
})
export class SearchComponent implements OnInit {
faSearch = faSearch;
countries: OneCountry[] = [];
searchTerm: any;
cachedCountries: OneCountry[] = [];
constructor(private countryService: CountryService) {}
ngOnInit(): void {}
onKeyPressEvent(event: KeyboardEvent): void {
this.getCountries();
}
getCountries(): void {
this.countryService.searchCountries().subscribe({
next: (countries) => (
(this.countries = countries),
(this.cachedCountries = this.countries),
console.log(this.countries)
),
});
}
search(value: string): void {
this.countries = this.cachedCountries.filter((val) =>
val.name.toLowerCase().includes(value)
);
}
}
這是模板檔案:
<div id="search-component" class="w-full md:w-[32rem] dark:bg-darkblue-100">
<div
class="w-full px-4 h-[53px] flex justify-around align-center shadow-md border rounded"
>
<figure class="w-1/6 grid place-items-center">
<fa-icon
class="text-darkblue-100 dark:text-white text-lg"
[icon]="faSearch"
></fa-icon>
</figure>
<input
class="w-5/6 h-full focus:outline-none dark:bg-darkblue-100"
placeholder="Search for a country..."
#searchBox
name="searchTerm"
id="search-box"
(input)="search(searchBox.value)"
[(ngModel)]="searchTerm"
(keypress)="onKeyPressEvent($event)"
/>
</div>
<ul class="mt-0 pl-0 relative z-20">
<li
class="z-20"
*ngFor="let country of countries | searchFilter: searchTerm; index as i"
>
<a
*ngIf="i < 10"
routerLink="/detail/{{ country.name }}"
class="z-20 border border-t-0 inline-block w-full md:w-[32rem] p-4 rounded shadow hover:bg-darkblue-100 hover:text-white dark:hover:bg-white dark:hover:text-black h-12 box-border"
>{{ country.name }}</a
>
</li>
</ul>
</div>
uj5u.com熱心網友回復:
“Angular 有太多特殊的怪癖”。我猜的問題是您沒有將 this.countries 重置為[]. 您可以模糊地接線:
<input
...
(blur)="onBlur()" />
然后在你的課上
onBlur(){
this.countries = [];
}
不過,您應該真正研究一下可觀察物件,并且正如@kinglish 在評論中提到的那樣,您有一個奇怪的輸入和一個按鍵。
uj5u.com熱心網友回復:
擺脫了大部分舊的東西并切換到可觀察的。現在看起來像這樣:
組件.ts:
import { Component, OnInit } from '@angular/core';
import { faSearch } from '@fortawesome/free-solid-svg-icons';
import { CountryService } from '../services/country.service';
import { OneCountry } from '../country';
import { Observable, Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css'],
})
export class SearchComponent implements OnInit {
faSearch = faSearch;
countries$!: Observable<OneCountry[]>;
private searchTerms = new Subject<string>();
constructor(private countryService: CountryService) {}
// Push a search item into the observable stream
search(term: string): void {
// if (term.length >= 3) {
//
// }
this.searchTerms.next(term);
}
ngOnInit(): void {
this.countries$ = this.searchTerms.pipe(
// Wait 300ms after each keystroke before considering search term
debounceTime(300),
// ignore new term if same as previous term
distinctUntilChanged(),
// Switch to new search observable each time the term changes
switchMap((term: string) => this.countryService.searchCountries(term))
);
}
搜索服務:
searchCountries(term: string): Observable<any[]> {
const url = `${this.countriesUrl}all?fields=name`;
if (!term.trim()) {
// If not search term, return empty country list
return of([]);
}
return this.http
.get<Country[]>(url)
.pipe(
map((country) =>
country.filter((val) => val.name.toLowerCase().includes(term))
)
);
}
模板:
<div id="search-component" class="w-full md:w-[32rem] dark:bg-darkblue-100">
<div
class="w-full px-4 h-[53px] flex justify-around align-center shadow-md border rounded"
>
<figure class="w-1/6 grid place-items-center">
<fa-icon
class="text-darkblue-100 dark:text-white text-lg"
[icon]="faSearch"
></fa-icon>
</figure>
<input
class="w-5/6 h-full focus:outline-none dark:bg-darkblue-100"
placeholder="Search for a country..."
#searchBox
name="searchTerm"
id="search-box"
(input)="search(searchBox.value)"
/>
</div>
<ul class="mt-0 pl-0 relative z-20">
<li
class="z-20"
*ngFor="
let country of countries$ | async;
index as i;
searchFilter: searchTerms
"
>
<a
*ngIf="i < 10"
routerLink="/detail/{{ country.name }}"
class="z-20 border border-t-0 inline-block w-full md:w-[32rem] p-4 rounded shadow hover:bg-darkblue-100 hover:text-white dark:hover:bg-white dark:hover:text-black"
>{{ country.name }}</a
>
</li>
</ul>
</div>
資源
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/413750.html
標籤:
