1
I have a small problem with script and I believe it is scope of Component. I use a script to scroll in firefox, because in Chrome works normally anchorScrolling. The problem is that if I call on the route where has the Nav bar and footer, on the daughter routes the script does not work, then I need to add it on each son. So far so good. The problem is that on each route I load it add the same script again.
That is, if the user navigates in 4 different routes, I will have 4 times the same script and so when I click something to scroll the function is executed 4 times. Does anyone know of an alternative?
The division of my project is like this, App, Site Component (where I call header, router-outlet and footer), and other routes like Home and About for example.
I do so:
export class InjectScript {
LoadScript(url: string) {
const body = <HTMLDivElement>document.body;
const script = document.createElement('script');
script.innerHTML = '';
script.src = url;
script.async = false;
script.defer = true;
body.appendChild(script);
}
}
and onInit of the components:
ngOnInit( ) {
this.inject = new InjectScript();
this.inject.LoadScript('assets/js/funcoes.js');
// obs: funcoes.js é o script que contem meu scroll
}
Note: I found this other question that seems to me the same problem I have, but has no suggestion of solution. Target Problem of Angular Components 2 with importing external Javascripts
UPDATING: I found that when I put a click event calling a function that does not exist, the error appears in the console but works the scroll normally in Firefox. example: (click)="ball()"
<a class="nav-link" [routerLink] = "['/sobre']" fragment="meuId"(click)="bolinha()" ></a>
But still do not know how to do without appearing the error.
Take a look at my answer https://answall.com/questions/304485/scripts-angular/304488#304488
– Eduardo Vargas
@Eduardovargas looked at his answer here, but injecting the script is not being the problem, but rather that it works only for the route that was injected. So I have to do for all routes. Example, I import at home, then I import again at About, and so on. Doing so works but loads several times the same <script>.
– Michael Lelis