Angular组件模板加载时如何从HTML调用全局JavaScript函数
Got it, since you can't use the TypeScript controller and need to trigger that global getData() function directly from your Angular component's HTML template once it's loaded, here are two straightforward workarounds that should do the trick:
Method 1: Use a Hidden Image to Trigger Load Event
Angular doesn't let you use onload directly on regular elements like <div> in component templates, but we can use a tiny, hidden image's load event to fire the function right after the template renders. We'll use a minimal base64-encoded GIF (it loads instantly with no external requests):
<!-- Place this at the end of your component's HTML template --> <img src="data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA=" style="display: none;" (load)="getData()" >
This works because the image will load immediately after the component template finishes rendering, triggering the load event which calls your global getData() function.
Method 2: Bind to the Window's DOMContentLoaded Event
If you need to wait until the entire page's DOM is fully ready (not just the component template), you can bind the window's DOMContentLoaded event directly in your template:
<div (window:DOMContentLoaded)="getData()"></div>
Keep in mind this will trigger later than the image method, as it waits for all page resources to load instead of just the component's template.
Quick Note on Why Onclick Worked
The onclick event works seamlessly because Angular allows binding to user interaction events directly in templates without restrictions. Load events, however, are only natively supported on media elements (images, scripts, etc.) or the window/document—hence the need for these little hacks to hook into the template load timing.
内容的提问来源于stack exchange,提问作者Eladerezador

