How would I provide a DOM element to a 3rd-party library in Angular 2?
For example, if Library
is the hypothetical 3rd-party library, and I had to do something like:
var fakeId = document.getElementById('fake'); // e.g. canvas or SVG element
var sirRender = Library.confiscate(fakeId);
sirRender.drawMustache(); // accesses canvas context or manipulates SVG
I am using Typescript
and ES6 decorator component syntax.
I'm imagining I can do something inside ngOnInit
like:
@Component({
...
})
export class SirRender {
...
ngOnInit() {
// do something here?
}
...
}
My specific use case:
I'm trying to use this library called VexFlow, which takes a canvas element and renders svg. Specifically, there is an example:
var canvas = $("div.one div.a canvas")[0];
var renderer = new Vex.Flow.Renderer(canvas, Vex.Flow.Renderer.Backends.CANVAS);
var ctx = renderer.getContext();
var stave = new Vex.Flow.Stave(10, 0, 500);
stave.addClef("treble").setContext(ctx).draw();
So, I'm hoping the answer will work for this ^^ case.
For HTML elements added statically to your components template you can use
@ViewChild()
:This doesn't work for dynamically generated HTML though.
but you can use
This is frowned upon though because it's direct DOM access, but if you generate the DOM dynamically already you're into this topic already anyway.
In fact you can reference the corresponding
ElementRef
using@ViewChild
. Something like that:elt
will be set before thengAfterViewInit
callback is called. See this doc: https://angular.io/docs/ts/latest/api/core/ViewChild-var.html.