Search code examples
angulartypescriptangular2-directivesangular-components

How to call $( document ).ready() jQuery function with in ngAfterViewInit() on Component class using angular 2


The code is

constructor(private el: ElementRef) { }

ngAfterViewInit() {

    this.loadScript('app/homepage/template-scripts.js');       


}

Solution

  • Angular let you avoid this jquery dependency with lifecycle events:

    (ordered by lifecycle)

    -ngOnChanges -ngOnInit -ngDoCheck -ngAfterContentInit -ngAfterContentChecked -ngAfterViewInit -ngAfterViewChecked -ngOnDestroy

    if you want to use the jquery function .ready, you should import jquery as dependency in your angular project, then import the relative module in your .ts file and call it inside of ngAfterViewInit:

    // In the console
    // First install jQuery
    npm install --save jquery
    // and jQuery Definition
    npm install -D @types/jquery
    
    -----
    
    import $ from 'jquery';
    //
    
    ngAfterViewInit() {
    // other stuffs
    
    if ($.ready()) {
        console.log('ready');
      }
    }

    my code above works.

    But i want to explain you that is bad practise, because you are going to put logic inside existing angular lifecycle logic.

    https://angular.io/guide/lifecycle-hooks

    Hope this helped