Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

284
Views
TS2339: La propiedad 'on' no existe en el tipo 'HTMLElement'

Estoy usando el código plotly en angular 2. Recibo un error para seguir el código. Remití este código.

mi código es:

 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]']); } );

Recibo un error para la función plotDiv.on('....'). ¿Hay alguna función alternativa para .on() en angular 2? Por favor, ayúdame. Me quedé aquí.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Para evitar este error puedes escribir:

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

document.getElementById('myDiv') devuelve HTMLElement . Este tipo no contiene on método porque este método se agrega dentro plotly-latest.min.js . Entonces, para silenciar la advertencia de mecanografiado, puede decir explícitamente compilar para no verificar los tipos para plotDiv

Ejemplo de Plunker

Otra forma es crear una definición de tipo como:

 interface PlotHTMLElement extends HTMLElement { on(eventName: string, handler: Function): void; } var plotDiv = <PlotHTMLElement>document.getElementById('myDiv') plotDiv.on('plotly_relayout', function() { });
about 4 years ago · Santiago Trujillo Report

0

Mi enfoque preferido es usar tipos de parámetros literales de cadena para declarar un tipo de retorno especializado para las funciones del selector DOM. Luego definimos propiedades y eventos que son específicos de estos elementos.

Esto es posible gracias a las interfaces abiertas de TypeScript.

 // 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); }; } }

Con esta declaración, su núcleo original se verificará. No hay necesidad de introducir aserciones de tipo y podemos mantener un estilo más declarativo. Además, esto sirve como documentación de nuestras expectativas del div myDiv, a nivel de API.

EDITAR:

Parece que puede estar usando jQuery, si es así, el enfoque es el mismo y el código es casi idéntico.

 declare global { interface JQueryStatic { ("#myDiv"): JQuery & { on('plotly_relayout', (eventdata: {/* fill this in as needed */}) => void); }; } }
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!