My app works perfectly if I copy exactly the built-in function from Twitter docs (https://dev.twitter.com/web/javascript/loading) into ngAfterViewInit function, but when I s
I know this is an old question, but I got a better solution than setting a timeout. The code I posted as solution in this question is broken since late Angular 4 or early Angular 5 - I don't remember. I will update my answer there too.
So, to fix this, just put the code in the constructor (so the widget loads before the view) like so:
import { Component, OnDestroy } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({ ... })
export class HomeComponent implements OnDestroy {
private twitter: any;
constructor(private _router: Router) {
this.initTwitterWidget();
}
initTwitterWidget() {
this.twitter = this._router.events.subscribe(val => {
if (val instanceof NavigationEnd) {
(window).twttr = (function (d, s, id) {
let js: any, fjs = d.getElementsByTagName(s)[0],
t = (window).twttr || {};
if (d.getElementById(id)) return t;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
t._e = [];
t.ready = function (f: any) {
t._e.push(f);
};
return t;
}(document, "script", "twitter-wjs"));
if ((window).twttr.ready())
(window).twttr.widgets.load();
}
});
}
ngOnDestroy() {
this.twitter.unsubscribe();
}
}
If I find any information on why previous code was broken, I'll update this answer. (Or if anyone else knows, feel free to edit this)