【发布时间】:2019-07-21 03:43:16
【问题描述】:
我的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 属性?
【问题讨论】:
标签: javascript angular html angular6