Search code examples
angularionic-frameworkionic4angular7

How to get nativeElement from @ViewChild in Ionic 4/Angular7?


I am using Ionic 4's ion-search like so:

     <ion-searchbar
            #searchbarElem
            (ionInput)="getItems($event)"
            (tap)="handleTap($event)"
            [(ngModel)]="keyword"
            (ngModelChange)="updateModel()"
            [cancelButtonText]="options.cancelButtonText == null ? defaultOpts.cancelButtonText : options.cancelButtonText"
            [showCancelButton]="options.showCancelButton == null ? defaultOpts.showCancelButton : options.showCancelButton"
            [debounce]="options.debounce == null ? defaultOpts.debounce : options.debounce"
            [placeholder]="options.placeholder == null ? defaultOpts.placeholder : options.placeholder"
            [autocomplete]="options.autocomplete == null ? defaultOpts.autocomplete : options.autocomplete"
            [autocorrect]="options.autocorrect == null ? defaultOpts.autocorrect : options.autocorrect"
            [spellcheck]="options.spellcheck == null ? defaultOpts.spellcheck : options.spellcheck"
            [type]="options.type == null ? defaultOpts.type : options.type"
            [disabled]="disabled"
            [ngClass]="{'hidden': useIonInput}"
            (ionClear)="clearValue(true)"
            (ionFocus)="onFocus()"
            (ionBlur)="onBlur()"
    >
    </ion-searchbar>

On click I run the following from within the component:

@HostListener('document:click', ['$event'])
private documentClickHandler(event) {
    if ((this.searchbarElem
            && !this.searchbarElem._elementRef.nativeElement.contains(event.target))
        ||
        (!this.inputElem && this.inputElem._elementRef.nativeElement.contains(event.target))
    ) {
        this.hideItemList();
    }
}

However, I am getting the following error:

ERROR TypeError: Cannot read property 'nativeElement' of undefined

I have tried setting timeouts and declaring searchbarElem as ElementRef with no luck.

I know this worked in Angular 2/Ionic 2 but now it is not. Did something change or is the shadow dom affecting thing? Any help would be appreciated, thanks.


Solution

  • You should use ViewChild with the read: ElementRef metadata property:

    @ViewChild("searchbarElem", { read: ElementRef }) private searchbarElem: ElementRef;
    

    and access the HTMLElement with this.searchbarElem.nativeElement:

    @HostListener('document:click', ['$event'])
    private documentClickHandler(event) {
        console.log(this.searchbarElem.nativeElement);
    }
    

    See this stackblitz for a demo (see the code in the Home page).