Angular 2 - Provide 3rd-party library with element

2019-07-27 22:06发布

问题:

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.