简体   繁体   English

Angular 9 - 本地参考,#,查看子,@ViewChild

[英]Angular 9 - Local Reference, #, View child, @ViewChild

I have recently upgraded my project to angular 9.我最近将我的项目升级到了 angular 9。

Issue:-问题:-

I am facing issue with Local Reference('#') in template.我在模板中遇到了 Local Reference('#') 的问题。

I get the value as 'undefined'.我得到的值为“未定义”。

Objective: I am trying to close mat-select on scroll.目标:我试图在滚动时关闭 mat-select。

Code:代码:

Html html

<mat-select (selectionChange)="showDataForLocation($event)"
            [(value)]="dataService.startinglocation"
            (openedChange)="selectPanelOpened($event)" 
            #mySelect>

      <mat-option  aria-selected="true" [value]="location.ExLocationName" 
                  *ngFor="let location of startingPointData?.ExLocation"> 
                    {{location.ExLocationName}}
      </mat-option>
</mat-select>

TS code TS代码

@ViewChild('mySelect', { static: true }) mySelect;

@HostListener('window:scroll', [])
  onWindowScroll() {

    this.mySelect.close();
  }

The above worked perfectly on Angular 5, however now it throws error on 9.以上在 Angular 5 上运行良好,但是现在它在 9 上抛出错误。


Uncaught TypeError: Cannot read property 'close' of undefined
    at DetailComponent.onWindowScroll (detail.component.ts:1378)
    at DetailComponent_scroll_HostBindingHandler (detail.component.ts:77)
    at executeListenerWithErrorHandling (core.js:21593)
    at wrapListenerIn_markDirtyAndPreventDefault (core.js:21635)
    at platform-browser.js:934
    at ZoneDelegate.invokeTask (zone-evergreen.js:400)
    at Object.onInvokeTask (core.js:40744)
    at ZoneDelegate.invokeTask (zone-evergreen.js:399)
    at Zone.runTask (zone-evergreen.js:168)
    at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:481)

You should change the static flag to false.您应该将静态标志更改为 false。

// query results available in ngOnInit
@ViewChild('foo', {static: true}) foo: ElementRef;

OR

// query results available in ngAfterViewInit
@ViewChild('foo', {static: false}) foo: ElementRef;

More information on that topic the official Angular's migration guide: https://angular.io/guide/static-query-migration有关该主题的更多信息,请参阅官方 Angular 的迁移指南: https : //angular.io/guide/static-query-migration

try this:尝试这个:

@ViewChild('mySelect', { static: true }) mySelect: matSelect;

@HostListener('window:scroll', [])
  onWindowScroll() {

    this.mySelect.close();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM