[英]Angular 6 - Setting a method as the `data-*` attribute for an element
我的component.ts
看起来像这样:
import { Component, OnInit, AfterViewInit, ElementRef, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
import { environment } from '../../../environments/environment';
@Component({
selector: 'app-requester',
template: '<div id="btn-dlg-container"></div></div>',
})
export class RequesterComponent implements OnInit, AfterViewInit {
private externalJSHost = 'URI pointing to external JS';
constructor(
@Inject(DOCUMENT) private document, private elementRef: ElementRef
) { }
ngOnInit() {
}
ngAfterViewInit () {
const s2 = document.createElement('script');
s2.type = 'text/javascript';
s2.src = this.externalJSHost; // external script
s2.id = 'dlshare';
s2.setAttribute('data-callback', this.callBackMethod); // This is where the problem is
document.body.appendChild(s2);
}
callBackMethod() {
console.log('SUCCESS !!!');
}
}
我创建的script
元素需要一个data-callback
属性,它应该是一个函数。 该函数在脚本执行后执行。
显然, Element.setAttribute ( documentation ) 只需要一个String作为第二个参数。
我如何重写它以便我可以将callBackMethod
设置为我动态创建的script
元素的data-callback
属性?
为什么不在脚本加载后直接调用该方法
实际上,您可以通过 window 对象定义一个全局函数并传递函数的名称(字符串)。
ngAfterViewInit () {
window.my_global_callback = (data) => {
console.log(data);
this.callBackMethod();
};
const s2 = document.createElement('script');
s2.type = 'text/javascript';
s2.src = this.externalJSHost; // external script
s2.id = 'dlshare';
s2.setAttribute('data-callback', 'my_global_callback');
document.body.appendChild(s2);
}
此外,如果您想让全局回调的名称动态化(如果您有多个组件实例并且您希望每个实例都有自己的回调,您可能希望这样做),您可以生成一个唯一的 id( How to generate UUID in angular 6 ) 将其保存在一个变量中并执行以下操作:
...
window[uniqueGlobalCallbackVarName] = (data) => {
console.log(data);
this.callBackMethod();
};
...
s2.setAttribute('data-callback', uniqueGlobalCallbackVarName);
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.