簡體   English   中英

從經典 HTML 調用 angular 組件方法

[英]Calling an angular component method from classic HTML

我正在嘗試從另一個 javascript 庫調用在 angular component.ts 中定義的 function

該庫支持管理單元,我可以在其中定義 HTML 元素,這些元素將被渲染(它們不是角度的一部分)。

這是我的 html (不在組件的模板中)

<button onclick='ping()'>PING Button</button>
<button onclick='pong()'>PONG Button</button>

如何從上面的 html 調用我的 component.ts 定義的pong組件方法

import { Component, OnInit, AfterViewInit, Inject, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';

function ping() {
  alert('PING PING');
}


@Component({ ...
})

export class Component implements OnInit, AfterViewInit { ...
 pong() { //This is the method I want to call from outside of the component's template
    alert('pong pong');
  }
}

我試過了,但它不起作用

<button (click)="pong()">PONG Button</button>

但我不知道正常調用“pong()”function

謝謝!

我猜你想使用 angular 的非角度庫,它有一個全局回調。 請注意,這可能會導致問題,因為您必須從 angular 管理非角度事物的生命周期。

從 angular 模板中,只能調用組件 class 上的方法,不能調用全局回調。 但是,您可以在組件 class 上創建一個方法,並從那里調用全局回調。

在此之前還有一件事:typescript 不知道您的全局回調,因此您必須明確聲明它,請參見示例。 這告訴 typescript 在 typescript 之外創建了一些東西,所以它會讓你調用它。

import { Component } from '@angular/core';

declare const libMethod: (any) => any;

@Component({
  selector: 'my-app',
  template: `
    <button (click)="myMethod($event)"></button>
  `,
  styleUrls: []
})
export class AppComponent  {

  public myMethod(param) {
    libMethod(param);
  }
}

如果您計划從多個 angular 組件中使用該庫,那么您可能希望創建一個服務,僅在其中聲明全局回調,然后在該服務上創建一個方法。 這樣,這個有點老套的聲明就不會散布在你的代碼中,而是包含在一個地方。 如果你升級/替換這個庫,它也會讓你的生活更輕松。


對評論中問題的回答:

TBH 我不完全了解情況。 (誰調用后端,當它返回 HTML 時?你來自 Angular,還是 lib?lib 是否處理 HTML?或者它是做什么的?)

一些建議:創建一個全局 singleton 服務,該服務將其方法之一放在 window (如果您在方法中使用this ,請不要忘記bind它)作為庫的回調。 當 lib 使用數據調用它時,無論誰/何時實際觸發 lib 執行它的操作,服務都將數據存儲在主題中,並且服務還提供數據的 observable(可能使用shareReplay(1)這樣消費者總能得到一些東西)。

這樣,實際顯示數據就相當容易了,您可以只使用async pipe,而不必關心數據最初是如何/何時到達那里的,也不必將組件的生命周期與服務同步。

此外,您可能需要使用https://angular.io/api/platform-browser/DomSanitizer#bypasssecuritytrusthtml但我不確定,因為我從來不需要注入 HTML。 說到哪...

重要的安全注意事項:如果您從 angular 外部注入 HTML,並且被劫持,那么您只是打開了您的頁面以供各種討厭的跨站點腳本編寫。

如果你真的需要這個,你可以在window object 中提供該方法

組件.ts

constructor()
{
    window['pong'] = () => this.pong();
}

pong()
{
    alert ('pong inside component')
}

然后在您的 html 中,您可以使用舊式事件處理程序

<button onclick="pong()">Pong</button>

這是一個stackblitz演示

注意:如果您有多個實現此解決方案的相同 angular 組件的實例,則您將只有一次該方法的實例。 如果需要,您可以將它們全部保存到一個數組中,但您需要知道要調用哪一個

暫無
暫無

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

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