I would like to restrict the search in searchbar to one of the both:
- User typed the ‘ENTER’ key
- User clicked the search icon
How shall I do that?
Is there a way to use ionic searchbar and receive event when the search icon was clicked?
I would like to restrict the search in searchbar to one of the both:
<input #box
(keyup.enter)="update(box.value)"
(blur)="update(box.value)">
check the official tutorial of Angular2.
https://angular.io/docs/ts/latest/guide/user-input.html
I want to use the custom ion-searchbar
see https://ionicframework.com/docs/v2/api/components/searchbar/Searchbar/
Here is my code I used ElementRef
and Renderer
to bind these events to the custom ion-serachbar
:
ionViewDidLoad() {
let searchInput = this.elementRef.nativeElement.querySelector('.searchbar-input');
if(searchInput != null) {
this.renderer.listen(searchInput, 'keyup' , (event) => {
if(event.keyCode == 13) {
this.search(searchInput.value);
}
});
}
let searchIcon = this.elementRef.nativeElement.querySelector('.searchbar-search-icon');
if(searchIcon != null) {
this.renderer.listen(searchIcon, 'click' , (event) => {
this.search(searchInput.value);
});
}
}
@naomip can you share your .html page?
Thx!
It’s just the regular ion-searchbar
in my HTML
<ion-searchbar ... ></ion-searchbar>
unable to get event . what could be the reason
The icon has pointer-events: none set in the scss… to receive the event you need to override this… I also found looking for it in AfterInit was too early for the element to have been rendered so ended up with this.
export class LocationSelectComponent implements OnDestroy, AfterViewChecked {
private unregisterClick?: Function;
private unregisterTouch?: Function;
constructor(
private eventManager: EventManager,
private elementRef: ElementRef
) {
}
ngAfterViewChecked() {
if (undefined === this.unregisterClick && undefined === this.unregisterTouch) {
const searchIcon: HTMLElement | null = this.elementRef.nativeElement.querySelector('.searchbar-search-icon');
if (searchIcon) {
searchIcon.style.pointerEvents = 'all';
this.unregisterClick = this.eventManager.addEventListener(searchIcon, 'click', this.onSearchIconClick.bind(this));
this.unregisterTouch = this.eventManager.addEventListener(searchIcon, 'touch', this.onSearchIconClick.bind(this));
}
}
}
ngOnDestroy() {
if (undefined !== this.unregisterClick) { this.unregisterClick(); }
if (undefined !== this.unregisterTouch) { this.unregisterTouch(); }
}
onSearchIconClick() {
console.log('search icon click');
}
}