简体   繁体   中英

Angular 6 - Setting a method as the `data-*` attribute for an element

My component.ts looks like this:

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 !!!');
  }

}

The script element that I have created needs a data-callback attribute which should be a function. This function is executed after the script is executed.

Apparently, Element.setAttribute ( documentation ) only takes a String as the second argument.

How do I rewrite this so that I can set the callBackMethod as the data-callback attribute for the script element that I have created dynamically?

Why not call the method directly once the script has loaded

Actually, you could define a global function via the window object and pass the name (string) of the function.

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);
 }

Furthermore, should you want to make the name of the global callback dynamic (you may want to if you have multiple instances of the component and you want each to have its own callback) you can generate a unique id ( How to generate UUID in angular 6 ) save it in a variable and do:

...
window[uniqueGlobalCallbackVarName] = (data) => {
      console.log(data);
      this.callBackMethod();
};
...
s2.setAttribute('data-callback', uniqueGlobalCallbackVarName);
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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