Reputation: 43
I used this line to define a canvas element in my view.xml:
<core:HTML content="<div class="wrapper col-6"><canvas id="
myChart"width="800"height="400"></canvas></div>">
</core:HTML>
Now I want to get the element in the controller but the typical this.getView().byId("myChart")
doesn't seem to work even though the site successfully loads a canvas with the ID.
Is there a way to get those types of elements defined inside a core:HTML
tag for the controller?
If not, is there a different way to create a canvas or other HTML elements so that I can refer to them with an ID / use them in the controller?
Upvotes: 3
Views: 1039
Reputation: 7250
The element created in this way is not 'registered' in UI5 framework like the other controls. byId()
only checks the internal register.
You can use jQuery
or standard JavaScript to fetch the element though, like $('#myChart')
or document.querySelector('#myChart')
.
You will find the code for this in Core.js
or Core-dbg.js
.
Upvotes: 6
Reputation: 56
Like Jorg said, byId is for retrieving controls. So if you were to put an id on the HTML control, you could retrieve that control and then call getDomRef() on it to get the outermost element, which in your example would be the div. If you'd further only put the canvas inside the HTML control, you'd get that.
If you're accessing the id of the canvas directly, like Jorg suggested, you'll run into trouble if you're going to use the view twice inside a page, because the id of the canvas isn't unique anymore.
There is a third and IMHO preferable option, that is to use html directly inside the view. First you'll need to declare a namespace for it, like
xmlns:html="http://www.w3.org/1999/xhtml"
preferably right on your View element.
Then you can write html directly in your xml view like this:
<html:div class="wrapper col-6"> <html:canvas id="mycanvas" width="800" height="400"></html:canvas> </html:div>
This way you're getting a proper (unique) id for your canvas and can access it as part of the view's dom with this.getView().getDomRef("-mycanvas")
. Note the extra leading dash, because of internal id generation inconsistency in UI5. Also note that getDomRef()
is considered protected, but I doubt it will change. Finally, remember that you can only get a domref for rendered controls, so you'll probably want to access it from an afterRendering event.
Upvotes: 3