Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Execute JS from file using AfterViewInit

Quite new to Angular 2, and after looking around for few hours I'd like to have some help.

I have a JS file with some generic functions. For example:

$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip(); 
});

This file contains in fact way more code. As you can imagine, I'd like to enable tooltips of all components. I can't simply include this file in index.html because subcomponents aren't present (yet) when the file is loaded.

After some digging, afterViewInit() came up. This post suggests to copy/paste JS code into ngAfterViewInit(). That's the ugly way (in my opinion)...

So here I come with 2 related questions:

1# Is there a way to execute JS code when a child component is loaded? For example, something like:

// In app.component.ts
ngAfterChildComponentLoaded(){
   // JS code here
}

This solution is quite interesting because I'm not forced to implement ngAfterViewInit() with the same content in all my components. But is it possible?

2# Is there a way to import JS code instrad of copy/paste it into ngAfterViewInit()? I don't want copy/paste 300 lines of JS code into 15 differents components (for obvious reasons).

Thanks a lot for your help!

like image 726
DavidL Avatar asked Dec 10 '22 16:12

DavidL


1 Answers

See the following for how to get external js files for a particular component in angular 2/4:

import { Component, OnInit , AfterViewInit} from '@angular/core';
import { Router } from '@angular/router';
declare var $: any;
@Component({
  moduleId: module.id,  
  selector: 'dashboard',
  templateUrl: './dashboard.html',
  styleUrls: ['./dashboard.css']
})
export class DashboardComponent implements OnInit,AfterViewInit {

 constructor() {}

  ngOnInit() {
  }
  ngAfterViewInit(){
    $.getScript('assets/assets/build/js/custom.min.js');
  }

}
like image 61
Ketan Chaudhari Avatar answered Dec 17 '22 09:12

Ketan Chaudhari