TS2339: Propert 'on' does not exist on type "HTMLElement"

I am using graphical code in angular 2. I am getting error for the following code. I named this code.

My code:

var plotDiv = document.getElementById('myDiv');
plotDiv.on('plotly_relayout',
    function(eventdata){
      alert( 'ZOOM!' + '\n\n' +
        'Event data:' + '\n' +
        JSON.stringify(eventdata) + '\n\n' +
        'x-axis start:' + new Date(eventdata['xaxis.range[0]'])+ '\n' +
        'x-axis end:' + new Date(eventdata['xaxis.range[1]']));
      var xVal = new Date(eventdata['xaxis.range[0]']);
      var yVal = new Date(eventdata['xaxis.range[1]']);
    }
  );

      

I am getting error for plotDiv.on ('....') function. Is there an alternative function for .on () in angular 2? Please help me. I am stuck here.

+3


source to share


2 answers


To prevent this error, you can write:

var plotDiv: any = document.getElementById('myDiv');
plotDiv.on('plotly_relayout', ...

      

document.getElementById('myDiv')

return HTMLElement

. This type does not contain a method on

because this method was added to plotly-latest.min.js

. So to turn off the typescript warning, you can explain what to compile so as not to check types forplotDiv



Plunger example

Another way is to define the type of the type:

interface PlotHTMLElement extends HTMLElement  {
  on(eventName: string, handler: Function): void;
}

var plotDiv  = <PlotHTMLElement>document.getElementById('myDiv')
plotDiv.on('plotly_relayout', function() {

});

      

+6


source


My preferred approach is to use string literal parameter types to declare a specialized return type for DOM selector functions. We then define properties and events that are specific to those elements.

This is possible thanks to the open-ended TypeScript interfaces.

// Assuming you using modules as you mention Angular 2
// if this is actually script code and not a module, remove the `declare global` wrapper

declare global {
  interface Document {
    // This only enhances the return type of getElementById for the exact selector "myDiv".
    getElementById("myDiv"): HTMLDivElement & {
      // intersection `&` is used to add the specialized event.
      on('plotly_relayout', (eventdata: {/* fill this in as needed */}) => void);
    };
  }
}

      

With this declaration, your original kernel will be typecheck checked. There is no need to introduce type assertions and we can support a more declarative style. It also serves to document our expectation of the myDiv div at the API level.



EDIT:

It looks like you can use jQuery, if so then the approach is the same and the code is almost identical.

declare global {
  interface JQueryStatic {
    ("#myDiv"): JQuery & {
      on('plotly_relayout', (eventdata: {/* fill this in as needed */}) => void);
    };
  }
}

      

0


source







All Articles