如何从离子4 / Angular7中的@ViewChild获取nativeElement?

jrq*_*ick 4 ionic-framework angular ionic4 angular7

我正在像这样使用Ionic 4的离子搜索:

     <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>
Run Code Online (Sandbox Code Playgroud)

单击时,我从组件内部运行以下命令:

@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();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

ERROR TypeError: Cannot read property 'nativeElement' of undefined
Run Code Online (Sandbox Code Playgroud)

我已经尝试设置超时并声明searchbarElem为ElementRef不走运。

我知道这在Angular 2 / Ionic 2中有效,但现在不行了。有什么变化吗?还是影子圆顶影响了事物?任何帮助,将不胜感激,谢谢。

fed*_*der 8

对于那些使用Angular 8和 Ionic 4 的人,可以在static: false不攻击原生元素的情况下设置标志。

@ViewChild('searchInput', {static: false}) searchInput: IonSearchbar;
Run Code Online (Sandbox Code Playgroud)

请参阅此 Stackoverflow线程


Con*_*Fan 6

您应该将ViewChild其与read: ElementRefmetadata属性一起使用:

@ViewChild("searchbarElem", { read: ElementRef }) private searchbarElem: ElementRef;
Run Code Online (Sandbox Code Playgroud)

并使用来访问HTMLElement this.searchbarElem.nativeElement

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

有关演示,请参见此堆栈闪电(请参见主页中的代码)。