Integrating @types/arcgis-js-api into an Angular 5 project

Incorporating arcgis-js-api types into my angular5 application has been a challenge. Whenever I attempt to import the types in multiple components, an uncaught reference error occurs: __esri is not defined. I made sure to include arcgis-js-api in the types array within the tsconfig.app.json file. Below is a snippet of my code.

  import { Component, OnInit, Input, ViewChild, ElementRef } from 
'@angular/core';
  import * as esriLoader from 'esri-loader';
  import { environment } from '../../../environments/environment';
  import Esri = __esri;

  @Component({
    selector: 'app-custom-widget',
    templateUrl: './custom-widget.component.html',
    styleUrls: ['./custom-widget.component.css']
  })
  export class CustomWidgetComponent implements OnInit {
    private _mapView: Esri.MapView;
    private _scriptOptions: any;

    @ViewChild('customWidget') widgetElement: ElementRef;
    @Input()
    set mapView(mapView: Esri.MapView) {
      if (!mapView) {
        return;
      }
      this._mapView = mapView;
      this.renderWidget();
    }
    get mapView(): Esri.MapView {
      return this._mapView;
    }

    constructor() {
      this._scriptOptions = {
        url: environment.arcgisAPIVersion
      };
    }

    ngOnInit() {

    }

    renderWidget(): void {
      esriLoader.loadModules([
        'esri/widgets/Widget'
      ], this._scriptOptions).then(([Widget]) => {
        const widgetProperties: Esri.WidgetProperties = {
          container: this.widgetElement.nativeElement
        };

        const widget: Esri.Widget = new Widget(widgetProperties);

        this._mapView.ui.add(widget, 'bottom-right');
      });
    }

  }

Answer №1

After some experimentation, I stumbled upon a solution that solved my issue-
I opted to consolidate all model definitions into one file that imports the namespace, allowing me to utilize the types across different components without encountering the pesky bug "ReferenceError: __esri is not defined, cannot use this namespace in multiple components".

For instance:
Create a file named esri.models.ts-

import esri = __esri;  
export interface esriMapView extends esri.MapView {}
export interface esriLayerView extends esri.LayerView {}

Then in your components:

import { esriMapView } from "../../modules/esri.models";
const mapView: esriMapView = new MapView({});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using React hooks and Typescript: I was expecting to see an assignment or function call, but instead, an expression was

After working as a React developer for quite some time, my workplace recently introduced Typescript, which I am still getting familiar with. I implemented a custom hook for managing cookies, but the function it returns is generating an error. Here's ...

Show Timing on the Y-Axis - Bubble Graph

Recently, I stumbled upon the Bubble Chart feature in ng2-charts. I am trying to display data based on time on the Y-axis and values on the X-axis. My dataset consists of x:[10,35,60], y:["7.00 AM"], with r having the same value as x. However, the sample d ...

Tips on setting a value to zero in Angular when there is no input

Is there a way to organize the data and show the PRN entries based on the date, for instance, when the month is January? If there is data for machine 1 with assetCode: PRN, it should be displayed under the header for children. Similarly, if there is data f ...

I am experiencing an issue where the mat-header-cell components are not appearing after navigating

After initially loading the page, mat-header-cell displays fine. However, upon navigating to a second page, refreshing it in the browser, and then returning to the original page, the mat-header-cell is no longer visible. It only reappears after manually re ...

The use of setState clashes with the getDerivedStateFromProps method

import React, { Component } from "react"; export interface MyComponentProps { display: boolean; } export interface MyComponentState { display: boolean; } export default class CustomComponent extends Component<MyComponentProps, MyComponen ...

Is there a method to initiate a 'simple' action when dispatching an action in ngrx?

Here's the scenario I'm facing: When any of the actions listed below are dispatched, I need to update the saving property in the reducer to true. However, currently, I am not handling these actions in the reducer; instead, I handle them in my ef ...

Angular 5.2: Component type does not contain the specified property

In my Formbuilder.Group method, I have included the properties as shown in the following TypeScript code: this.form = this.fb.group({ caseNumber: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(50), Val ...

What could be causing the discrepancy in alignment between a web application running on Mac and Windows using ReactNative?

We have a web application built with react native. The alignment of the columns in the list is causing issues when running the app on Windows versus Mac, as illustrated in the screenshots. Interestingly, this problem only occurs with this specific list tha ...

Navigating back to the login page in your Ionic V2 application can be achieved by utilizing the `this.nav

Running into an issue with navigating back to the login screen using Ionic V2. Started with the V2 tabs template but added a custom login page, setting rootPage = LoginPage; in app.components.ts. When the login promise is successful, I used this.nav.setR ...

Using Typescript to pass an interface as an argument to a function that requires a JSON type

Here is an extension related to the topic of Typescript: interface that extends a JSON type Consider the following JSON type: type JSONValue = | string | number | boolean | null | JSONValue[] | {[key: string]: JSONValue} The goal is to inform type ...

Is there a way to turn off linting while utilizing vue-cli serve?

I am currently running my project using vue-cli by executing the following command: vue-cli-service serve --open Is there a way to stop all linting? It seems like it's re-linting every time I save, and it significantly slows down the process of ma ...

Storing the state of DevExtreme DataGrid in Angular

Currently, I have integrated the DevExtreme DataGrid widget into my Angular application. Here is a snippet of how my DataGrid is configured: <dx-data-grid id="gridContainer" [dataSource]="employees" [allowColumnReordering]="true" [allo ...

Transfer only designated attributes to object (TS/JS)

Is it feasible to create a custom copy function similar to Object.assign(...) that will only copy specific properties to the target? The code snippet I have is as follows: class A { foo?: string; constructor(p: any) { Object.assign(this, p ...

Utilize @types for the Typescript npm library without the need for downstream projects to install this dependency

Our npm library package, built in TypeScript and known as lib-utils, provides a range of utilities for other projects to leverage. One of the dependencies within lib-utils is d3, which is both a peerDependency and a devDependency. Additionally, there is a ...

Angular 2: The linting error shows up as "Anticipated operands need to be of the same type or any"

So, I have this shared service file where a variable is defined like so: export class SharedService { activeModal: String; } Then, in my component file, I import the service and define it as follows: constructor(public sharedService: SharedService) ...

Incorporate a random number generation within a specified index range while looping in Angular

I am working with an array that contains static images: public ImageList: Array<any> = [ {"id" : 1, "Url" :"assets/images/...svg"}, {"id" : 2, "Url" :"assets/images/...svg"}, { ...

Assigning to a constrained type with an indexable signature results in failure

When using typescript 4.7.2, I encountered an issue where the following code fails only when assigning a value: type IndexableByString = { [k: string]: any }; function test<T extends IndexableByString>(target: T, key: string) { var prop = target ...

What is the method to invoke a function within another function in Angular 9?

Illustration ` function1(){ ------- main function execution function2(){ ------child function execution } } ` I must invoke function2 in TypeScript ...

Associating function parameters with object types in TypeScript

In the conclusion of this post, I provide operational code for associating object types with a function that accepts an object containing matching properties. The code snippet I shared results in 'result' being resolved as: type result = { GE ...

ReactTS: Tips for organizing child components within a "container component"

Currently, I am in the process of developing reusable front-end components in React using Typescript. However, I am encountering a challenge related to a feature commonly found in traditional packages. My goal is to have the ability to nest children of a ...