Simple question, I hope.
I want to run a script when the Angular2 equivalent of $document.ready() is fired. What is the best way to achieve this?
I've tried putting the script at the end of index.html
, but as I found out, this doesn't work! I take it that it has to go in some kind of component declaration?
Is it possible to run load the script from a .js
file?
EDIT - Code:
I've got the following js and css plugins injected into my application (from the Foundry html theme).
<link href="css/themify-icons.css" rel="stylesheet" type="text/css" media="all" /> <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" /> ... <script src="js/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/flexslider.min.js"></script> ... <script src="js/scripts.js"></script> //This initiates all the plugins
As noted, the scripts.js 'instantiates' the whole thing, and thus is needed to be run after Angular is ready. script.js
Got it working:
import {Component, AfterViewInit} from 'angular2/core'; @Component({ selector: 'home', templateUrl: './components/home/home.html' }) export class HomeCmp implements AfterViewInit { ngAfterViewInit() { //Copy in all the js code from the script.js. Typescript will complain but it works just fine }
Answer: Use the DOMContentLoaded Event You can utilize the JavaScript Window's DOMContentLoaded event to construct $(document). ready() equivalent without jQuery.
The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.
So technically it doesn't matter where you put it. Many people like putting script in the head, because it makes sure the script is read before the page is loaded. Other people like putting it at the very end (just before the end body tag) so that all of the elements of the page are loaded before the script reads them.
So, there is no event called after document. ready(). You'll need to create and wait for events to complete on your own, or use window. load().
Copying the answer from Chris:
Got it working:
import {AfterViewInit} from 'angular2/core'; export class HomeCmp implements AfterViewInit { ngAfterViewInit() { //Copy in all the js code from the script.js. Typescript will complain but it works just fine }
You can fire an event yourself in ngOnInit()
of your Angular root component and then listen for this event outside of Angular.
This is Dart code (I don't know TypeScript) but should't be to hard to translate
@Component(selector: 'app-element') @View( templateUrl: 'app_element.html', ) class AppElement implements OnInit { ElementRef elementRef; AppElement(this.elementRef); void ngOnInit() { DOM.dispatchEvent(elementRef.nativeElement, new CustomEvent('angular-ready')); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With