@viewChild not working - cannot read property nativeElement of undefined

后端 未结 8 1863
孤街浪徒
孤街浪徒 2020-12-05 06:00

I\'m trying to access a native element in order to focus on it when another element is clicked (much like the html attribute \"for\" - for cannot be used on elements of th

相关标签:
8条回答
  • 2020-12-05 06:53

    This error occurs when you're trying to target an element that is wrapped in a condition.

    So, here if I use ngIf in place of [hidden], it will give me TypeError: Cannot read property 'nativeElement' of undefined

    So use [hidden], class.show or class.hide in place of *ngIf.

    <button (click)="displayMap()" class="btn btn-primary">Display Map</button>
    
       <div [hidden]="!display">
          <div #mapContainer id="map">Content to render when condition is true.</div>
       </div>
    
    0 讨论(0)
  • 2020-12-05 07:02

    Sometimes, this error occurs when you're trying to target an element that is wrapped in a condition, for example: <div *ngIf="canShow"> <p #target>Targeted Element</p></div>

    In this code, if canShow is false on render, Angular won't be able to get that element as it won't be rendered, hence the error that comes up.

    One of the solutions is to use a display: hidden on the element instead of the *ngIf so the element gets rendered but is hidden until your condition is fulfilled.

    Read More over at Github

    0 讨论(0)
提交回复
热议问题