简体   繁体   English

在angular2中包装第三方组件

[英]wrapping 3rd party components in angular2

I want to use 3rd party ui elements/components in my angular2 app like eg spin.js . 我想在我的angular2应用程序中使用第三方ui元素/组件,例如spin.js。 To use this library I would have to directly access the DOM which is not really the way it should be done in angular2 (for several reasons like for example server-side rendering): 要使用这个库,我必须直接访问DOM,这实际上并不是应该在angular2中完成的方式(出于几个原因,比如服务器端渲染):

var target = document.getElementById('foo')
var spinner = new Spinner(opts).spin(target);

Is there any advice on how to deal with such 3rd party libraries in angular2? 关于如何在angular2中处理这样的第三方库,有什么建议吗? Or is direct DOM manipulation the only way for now? 或者是直接DOM操作现在的唯一方法?

I would wrap it into a custom directive: 我会把它包装成一个自定义指令:

@Directive({
  selector: '[spinner]'
})
export class SpinnerDirective {
  constructor(private elementRef:ElementRef.nativeElement) {
  }

  ngAfterViewInit() {
    var spinner = new Spinner(opts).spin(this.elementRef);
  }
}

and use it this way: 并以这种方式使用它:

@Component({
  (...)
  template: `
    <span spinner>...</span>
  `,
  directives: [ SpinnerDirective ]
})
export class SomeComponent {
  (...)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM