将外部css和javascript文件导入Angular 4

时间:2017-11-12 16:35:23

标签: angular angular2-forms angular-forms

我有一个javascript文件和一个css文件,我想在我的angular 4应用程序中使用。

我尝试在angular-cli.json文件中导入它们,如下所示:

  "styles": [
    "../../../bootstrap-combobox/js/bootstrap-combobox.min.css",
    "./styles.scss"
  ],
  "scripts": [
    "../../../bootstrap-combobox/js/bootstrap-combobox.min.js"
  ],

但它似乎不起作用。我确保文件的路径是正确的。

为了使这项工作,我需要使用jQuery为函数分配一个html元素,所以我这样做:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import * as jQuery from '../../../node_modules/jquery'

@Component({
  selector: 'app-billgenerator',
  templateUrl: './billgenerator.component.html'
})
export class BillgeneratorComponent implements OnInit {
  constructor() { }
  ngOnInit() {}

  ngAfterViewInit() {
    jQuery(document).ready(function () {
    jQuery(".chosen").combobox();
  });
  }
}

这是html元素,我想将它应用于:

<select class="chosen">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
</select>

我做错了什么? 我最近开始学习Angular,所以我对它不太了解。

1 个答案:

答案 0 :(得分:0)

使用npm

安装jQuery
npm install --save jquery
npm install -D @types/jquery

添加:

"scripts": [
 "../node_modules/jquery/dist/jquery.min.js",
],

并像这样导入

import * as $ from 'jquery';

并使用它whay:

 ngAfterViewInit() {
  $(document).ready(function () {
  $(".chosen").combobox();
 });

如果jQuery是自动集成的,你可以导入你的js文件