Kenny Ho
Kenny Ho

Reputation: 423

Twitter timeline embed doesn't reload in Angular

Im trying to get my twitter timeline embed to refresh after an event where I change the a Subject item from a service. This will then change the href of the twitter embed in the template.

The first event (a button that selects a twitter profile), works correctly showing the twitter timeline for that particular Subject item.

However, consequent button clicks on other profiles doesn't trigger a new twitter timeline. It does change the template href, but it doesn't show its twitter timeline.

I'm Using this https://stackoverflow.com/a/47178554/7106485 to create the twitter window for the timeline.

Component Code:

export class HighlightSocialComponent implements OnInit, OnDestroy {
  team1Social: TeamSocial = new TeamSocial();
  twitterUrl = 'https://twitter.com/lakers';
  private twitter: any;
  @ViewChild('t') twitterElement: ElementRef;

  constructor(private teamService: TeamsServices, @Inject(PLATFORM_ID) private platformId: Object) {}

  ngOnInit() {
    this.teamService.homeTeamSocialChanged.subscribe(
      (ts: TeamSocial) => {
        this.team1Social = ts;
        this.twitterUrl = this.getTwitterUrl(ts.twitter);
        // https://stackoverflow.com/questions/47176195/embedded-twitter-widget-on-angular-2-app-only-shows-up-on-the-first-page-load?noredirect=1&lq=1
        if (isPlatformBrowser(this.platformId)) {
          setTimeout(function() {
            (<any>window).twttr = (function(d, s, id) {
              let js, fjs = d.getElementsByTagName(s)[0],
                t = (<any>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) {
                t._e.push(f);
              };
              return t;
            }(document, 'script', 'twitter-wjs'));
            (<any>window).twttr.widgets.load(); }, 100);
        }
      });
  }

Template Code:

<a class="twitter-timeline" data-lang="en" data-height="400" data-theme="light" data-chrome="noborders nofooter noheader noscrollbar transparent"
   [href]="twitterUrl | safeUrl " #t></a>

Upvotes: 1

Views: 893

Answers (2)

Emeric
Emeric

Reputation: 6885

Try the following:

ngAfterViewInit(): void {
   (<any>window).twttr.widgets.load();
}

It worked like a charm for me using Angular 7.

Upvotes: 1

Kenny Ho
Kenny Ho

Reputation: 423

Found a Solution:

I used a ngIf with a property that explicitly listens to when the "profile" had changed. When it is called, I toggled (setting off/then on) that property so that div refreshes and clears the twitter window. Then new twitter timeline would now be able to load.

Upvotes: 0

Related Questions