I am trying to use a clickable SVG map to navigate to different pages.
Using the onclick event on the SVG areas works well and I can put a message to the console or give an alert(), for instance.
However, I don’t know how to reach a method on one of my TS classes. Directly trying something like MapsPage.gotoZone(2); fails because “MapsPage is not defined”.
Is there a way to reach Ionic 2 classes/methods from javascript global scope (I believe this is what’s used in the SVG object).?
Or maybe there is a more simple approach to accomplish this task. Any help will be greatly appreciated.
Instead to trying to reach my typescript classes from the SVG, I am attaching now the click event from my class into the SVG regions like this:
ionViewWillEnter() {
let map = document.getElementById("mapObject");
let myPage = this;
// object will load external SVG asynchronously
map.addEventListener("load", function() {
// The cast is to avoid typescript error: "Property 'contentDocument' does not exist on type 'HTMLElement'"
// Type is probably not correct, but have the desired property...
let svgDoc = (<HTMLIFrameElement>map).contentDocument; // Get the inner SVG DOM
let zones = svgDoc.querySelectorAll("[id^=MyZone]"); // Query by id pattern
for (let i = 0, l=zones.length; i < l; ++i) {
let item = zones[i];
item.addEventListener("click", function() { // Attach desired event
let myId= this.id.split('_')[1];
alert(myId+": Moving to page #"+myId);
myPage.gotoPage(myId);
}, false);
}
},false);
}
By the way, attaching Angular (click) events seems to work when the SVG is directly created in the template, but doesn’t when the SVG comes from an external file, which seems logical to me.
Yes, that’s the idea. Javascript will happily execute the sentence:
var map = document.getElementById("mapObject");
var svgDoc = map.contentDocument;
But in typescript the first sentence returns an HTMLElement, which does NOT have the contentDocument property. It will, however, execute it somehow in browser (because the property really exists in the object), but the compiler will fail with a type error and would not generate code for the device.
The correct way is to provide the type for the compiler:
var map = document.getElementById("mapObject") as HTMLObjectElement ;
var svgDoc = map.contentDocument;