模糊事件未重置值



我有一个搜索栏功能,我使用ngOnChanges来检测搜索词的变化,使我能够过滤一些数据。但是,如果我再次使用以前的搜索词值,则不会捕捉到此更改。现在我知道这是有道理的,因为实际上,搜索词属性没有变化。

似乎当我使用搜索栏中的"x"清除按钮时,我可以再次使用相同的搜索词。然而,如果我要从搜索栏中删除焦点,然后尝试重复搜索词,这是不起作用的。

我的.ts:

@Component({
selector: 'app-orders-list',
templateUrl: './orders-list.component.html',
styleUrls: ['./orders-list.component.css'],
})
export class OrdersListComponent implements OnChanges, AfterViewInit{

@Input() searchTerm: string; // <----
ngOnChanges(changes: SimpleChanges): void {
// searchTerm comes from parent component, if it changes then a new search is active
// want to detect when the current value equals previous value
if (changes.searchTerm) {
if(changes.searchTerm.currentValue === "") {
/* do stuff */
}
else{
/* do stuff */
}
}
...
}
...
}

搜索栏.ts:

@Component({
selector: 'app-toolbar',
templateUrl: './orders-toolbar.component.html',
styleUrls: ['./orders-toolbar.component.css'],
})
export class OrdersToolbarComponent implements OnInit {
@ViewChild('searchInput') searchInput: ElementRef;
@Output() searchTerm = new EventEmitter<string>();
@Output() isSearchActive = new EventEmitter<boolean>();
hideSearchBar: boolean;
searchString: string;
searchStringUpdate = new Subject<string>();
ngOnInit(): void {
this.searchString = "";
this.hideSearchBar = true;
this.searchStringUpdate.pipe(
debounceTime(500),
distinctUntilChanged())
.subscribe(() => {
this.onSearchChange();
}
);
}
resetSearchBar() {
this.searchString = "";
this.onSearchChange();
this.hideSearchBar = true;
this.onSearchBarContext(false);
}
showSearchBar() {
this.searchInput.nativeElement.focus();
this.hideSearchBar = false;
this.onSearchBarContext(true);
}
onSearchChange() {
this.searchTerm.emit(this.searchString);
}
onSearchBarContext(isActive: boolean){
this.isSearchActive.emit(isActive);
}
clearSearch(){
this.searchString = "";
this.onSearchChange();
}
}

对于搜索栏。html:

<div id="search" class="hide-searchbar" [ngClass]="{'show-searchbar': this.hideSearchBar === false}">
<input
id="searchbar"
type="search"
autocomplete="off"
[(ngModel)]="searchString"
(ngModelChange)="this.searchStringUpdate.next($event)"
(blur)="resetSearchBar()"
(search)="clearSearch()"
(keydown.escape)="searchInput.blur()"
#searchInput
/>
</div>
...
...

提前谢谢。

ngOnInit内部的订阅中删除distinctUntilChanged运算符就成功了。

像这样:

ngOnInit(): void {
this.searchString = "";
this.hideSearchBar = true;
this.searchStringUpdate.pipe(
debounceTime(500))
.subscribe(() => {
this.onSearchChange();
}
);
}

顾名思义,distinctUntilChanged只有在当前值与上一个值不同时才会发射。

最新更新