0

I have an element in an Angular2 app that loads fine when I refresh the page or go to it initially, but is hidden when I change the route to the parent page. I am using some purchased styles/js and when I searched the element name I found some functions inside of a .ready() call that show the element and adjust its height. I believe the issue is that these init scripts run the first time, but then when I change routes they do not execute. I need these scripts throughout the website and I can't really split them up because they're minified. I tried just popping all the scripts into the bottom of the component's HTML but this did not work (not that I expected it to).

If this isn't enough info I can pastebin the js and the element in question but this seems to me like something that would come up a lot and therefore have an easy, generic fix.

3
  • So far my best (horrible) solution is: this.router.events.subscribe((evt) => { if (evt instanceof ResolveStart && this.router.url !== '/home' && evt.url == '/home' && this.router.url !== '/' && this.router.url !== evt.url){ window.location.href = window.location.origin; }}) Commented Apr 16, 2018 at 1:20
  • I have added one more solution, you can try that. Commented Apr 16, 2018 at 3:22
  • @SneakyBeaver his solution will work for you. Post it as an answer. Commented Apr 17, 2018 at 12:24

2 Answers 2

2

This happened to me with a theme that wasn't Angular ready as well, I'm pretty sure that there should be a cleaner way to solve it at this time, but it worked for me at that moment. Load your theme's js library into your main component:

ngAfterViewInit() {
    if (document.getElementById("yourLibUniqueId")) {
        document.getElementById("yourLibUniqueId").remove();
    }

    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "lib/yourLib.js";
    s.id = "yourLibUniqueId";
    this.elementRef.nativeElement.appendChild(s);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use activate method of router-outlet as:

<router-outlet (activate)="onActivate($event)"></router-outlet>

Then in onActivate do whatever you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.