简体   繁体   中英

How to include external javascript files in Angular?

I've been messing around in Angular and I am trying to include an external .js file but Angular keeps ignoring it. I tried including the file in the <header> .

I tried including it by using the styleUrl inside the component

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  stylesUrl: ['/js/bootstrap.min.js']
})

but nothing seems to work.

How should I been doing this?

Add a script tag to your index.html file (or equivalent) and set the src as the JavaScript file. Then when the page is requested it will have the file included. If you need to call specific bootstrap methods you will want to import the library inside your component using module imports to reference it inside your TypeScript code.

Your question is specific to Angular 2 and stylesUrl is for css not js.

Wiring up dependencies in Angular 2 is done in different ways depending on what the dependency is. Dependencies can be wired by extending a class, injecting a dependency, or adding an annotation in nice cases. In non-nice cases hacks may be required. Here is the official documentation on dependency injection .

It looks like you care about Bootstrap in particular. Here is how you can inject Bootstrap into an ng2 component .

On styleUrl, you should include the style files. And you can include the external javascript or css files on angular.json (from Angular 6+) or angular-cli.json (before Angular 6).

Or simply, you can include those on index.html.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM