Skip to content Skip to sidebar Skip to footer

Angular 2 - Provide 3rd-party Library With Element For Rendering

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 = d

Solution 1:

In fact you can reference the corresponding ElementRef using @ViewChild. Something like that:

@Component({
  (...)
  template: `
    <div #someId>(...)</div>
  `
})
exportclassRender {
  @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.

Solution 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.

Post a Comment for "Angular 2 - Provide 3rd-party Library With Element For Rendering"