Angular 2 - Provide 3rd-party library with element for rendering

喜欢而已 提交于 2020-01-25 04:13:17

问题


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.


回答1:


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 will be set before the ngAfterViewInit callback is called. See this doc: https://angular.io/docs/ts/latest/api/core/ViewChild-var.html.




回答2:


For HTML elements added statically to your components template you can use @ViewChild():

@Component({
  ...
  template: `<div><span #item></span></div>`
})
export class SirRender {
  @ViewChild('item') item;
  ngAfterViewInit() {
    passElement(this.item.nativeElement)
  }
  ...
}

This doesn't work for dynamically generated HTML though.

but you can use

this.item.nativeElement.querySelector(...)

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.



来源:https://stackoverflow.com/questions/36572941/angular-2-provide-3rd-party-library-with-element-for-rendering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!