簡體   English   中英

從生成的 html 調用 .ts 文件中的函數<script>

[英]Calling function in .ts file from html generated by <script>

在從<script>生成后,我試圖從我的 html 調用doThis()函數。

因為它是一個運行外部 url 的腳本,所以我需要在我的 .ts 文件中使用一個變量來添加它。 它可以毫無問題地執行並創建我的 html 元素。 該 html 元素是一個付款表單,當它完成時,它會調用內部的函數並將訂單信息作為參數提供給我。

我的問題是我試圖從該 html 函數調用 .ts 文件中的函數以使用該訂單信息,但我找不到從我的 html 內部引用該 .ts 函數的方法。

.ts 文件

export class Component implements OnInit {

    giftupHtml: string = `<script type="text/javascript">
                            (function (g, i, f, t, u, p, s) {
                                g[u] = g[u] || function() { (g[u].q = g[u].q || []).push(arguments) };
                                p = i.createElement(f);
                                p.async = 1;
                                p.src = t;
                                s = i.getElementsByTagName(f)[0];
                                s.parentNode.insertBefore(p, s);
                            })(window, document, 'script', 'https://cdn.giftup.app/dist/gift-up.js', 'giftup');

                            // Track conversions:
                            giftup("conversion", function (payload) { 
                                   doThis();
                            });
                           </script>
                           `;

    constructor( ) { }

    doThis() {
        console.log("This isn't called.");
    }

基本上,giftupHtml 在 . 它呈現得很好,我知道調用了 html 函數,因為我可以使用 console.log(payload) 但我無法引用我的 .ts 文件或函數。

您在 Angular 區域之外調用的任何內容都需要包含在來自 ngZone 的調用中。 並確保您使用箭頭函數,以便對 this 的引用保留為組件。

constructor(ngZone: NgZone) {
  window['doThis'] = () => {
    ngZone.run(() => {
      // Now you have full access to the component here
    });
  };
}

ngOnDestroy() {
  delete window['doThis'];
}

實際上,您嘗試從腳本窗口訪問 angular 函數是正常的,您通常無法這樣做,但有一些解決方法https://www.c-sharpcorner.com/blogs/call-angular-2-function-from-javascript但我你真的對你這樣做的原因感興趣嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM