5

I am working to get a ArcMap Javascript for Angular (v4) to display a map in a Angular (v10) project. All the code samples (here, ESRI Offical here, and stackblitz here) I have found are very similar. The viewChild is created like this :

export class EsriMapComponent implements OnInit, OnDestroy {
@ViewChild("mapViewNode", { static: true }) private mapViewEl: ElementRef;
view: any;
constructor() { }

But my IDE informs me that TS2564 Property mapViewEl has no initializer and is not definitely assigned in the constructor.

I can change this line to :

@ViewChild("mapViewNode", { static: true }) private mapViewEl!: ElementRef;

And the map is drawn, but I don't like removing Typescript protection, especially since it is not done in any of the working samples I have found online.

The esri-map.component.html is very simple : <div #mapViewNode></div>.

How can I fix the TS2564 error?

1 Answers1

2

My suggestion is to use the optional operator (?) instead of not-null assertion (!). Because the property is actually undefined until the component is rendered, so, eventually you'll need to manage potentially undefined values in the property. Besides, if the component name in @ViewChild('compName') is not correct the property will be undefined so if you mark it as optional It sounds more realistic than the not-null alternative.

@ViewChild("mapViewNode", { static: true }) private mapViewEl?: ElementRef;
Roberto
  • 8,586
  • 3
  • 42
  • 53