Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 9 - Local Reference, #, View child, @ViewChild

I have recently upgraded my project to angular 9.

Issue:-

I am facing issue with Local Reference('#') in template.

I get the value as 'undefined'.

Objective: I am trying to close mat-select on scroll.

Code:

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

@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.


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)

like image 336
Anand Kumar Avatar asked Feb 26 '20 09:02

Anand Kumar


1 Answers

You should change the static flag to 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

like image 155
Florent Arlandis Avatar answered Sep 27 '22 21:09

Florent Arlandis