Angular 2 - Provide 3rd-party library with element

2019-07-27 22:18发布

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.

2条回答
Juvenile、少年°
2楼-- · 2019-07-27 22:26

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.

查看更多
贪生不怕死
3楼-- · 2019-07-27 22:51

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.

查看更多
登录 后发表回答