I' trying to call a doThis()
function from my html after it has been generated from a <script>
.
Because it is a script that runs an external url, I need to add it using a variable in my .ts file. It executes with no problem and creates my html element. That html element is a payment form, when it is completed, it calls a function that is inside the and gives me the order information as parameter.
My problem here is I'm trying to call a function in my .ts file from that html function to use that order information but I can't find a way to reference that .ts function from inside my html.
.ts file
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.");
}
Basically the giftupHtml is used as [innerHTML] inside a . It renders fine and I know the html function is called since I can console.log(payload) but I can't reference my .ts file or function.
Anything you call outside the Angular zone will need to be wrapped in a call from ngZone. And make sure you use arrow functions so that the references to this stay as the component.
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但我你真的对你这样做的原因感兴趣吗?
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.