Roka545 Roka545 - 6 days ago 5
Javascript Question

Get modal element in Angular 2 typescript.

How do you use document.getElementById to get a modal element? I'm trying to manually show and hide a modal via code in my home component typescript file.

I already have a working modal that works when a button is pressed - now I want to manually toggle the modal when certain conditions occur in code.

I have:

var errorModalBox = document.getElementById("errorModal");
errorModalBox.modal('show');


However, the second line throws the following error:

Property 'modal' does not exist on type 'HTMLElement'.

Answer

As your error explains, the "modal" property does not exist on the "HTMLElement". This is because you are obtaining a reference to the HTML element with pure JavaScript and not JQuery. Jquery adds additional methods when referencing HTML elements, Bootstrap JS adds additional methods and properties to the jQuery object; one of which is the "modal" method.

Since you are using Typescript with Angular 2, the typescript compiler will throw an error when you reference the jQuery object using "$" or "jQuery". To fix the compile error, add this statement below the last import statement in your Home Component.

declare var $:any;

Then just change your code from:

var errorModalBox = document.getElementById("errorModal");
errorModalBox.modal('show');

To:

$('#errorModal').modal('show');
Comments