Angular 2-为第3方库提供渲染元素 [英] Angular 2 - Provide 3rd-party library with element for rendering
问题描述
如何为Angular 2中的第3方库提供DOM元素?
How would I provide a DOM element to a 3rd-party library in Angular 2?
例如,如果Library
是假设的第三方库,那么我必须做类似的事情:
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
我正在使用Typescript
和ES6装饰器组件语法.
我在想我可以在ngOnInit
内部做某事,例如:
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:
我正在尝试使用名为 VexFlow 的该库,该库需要一个canvas元素并渲染svg.具体来说,有一个示例:
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.
推荐答案
实际上,您可以使用@ViewChild
引用相应的ElementRef
.像这样的东西:
In fact you can reference the corresponding ElementRef
using @ViewChild
. Something like that:
@Component({
(...)
template: `
<div #someId>(...)</div>
`
})
export class Render {
@ViewChild('someId')
elt:ElementRef;
ngAfterViewInit() {
let domElement = this.elt.nativeElement;
}
}
elt
将在调用ngAfterViewInit
回调之前设置.请参阅此文档: https://angular.io/docs/ts/latest/api/core/ViewChild-var.html .
elt
will be set before the ngAfterViewInit
callback is called. See this doc: https://angular.io/docs/ts/latest/api/core/ViewChild-var.html.
这篇关于Angular 2-为第3方库提供渲染元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!