iT邦幫忙

2

如何在 Angular 4 中加入 jQuery

前言

jQuery 幾乎是必要的 module 了,不管是想用 Bootstrap 或是使用一些 jQuery 開發出的套件,一定都必須先引入 jQuery

大致上可以分為兩中方法引入,一個是直接在 index.html 直接嵌入 script,一個則是在 Angular Cli(或類似功用的 Cli) 中引入 module

方法一

index.html<head> 裡面加上這個 tag

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

然後再要用 jQuery 的組件中宣告他

import { Component } from '@angular/core';
declare var jquery:any; // 這邊用 var 
declare let $:any; // 當然 let 也可以

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular 4 with jQuery';
  hideTitle(){
    $('.title').hide();
  }

}

然後在對應的 html 可能長這樣

<h1 class="title">
  {{title}}
</h1>
<button (click)="hideTitle()"> clickhere</button>

這樣就可以用了,只是第一個方法比較適合在小網站上,大網站比較適合採第二個方法引入 module

這邊可以點來看 Plunker Demo

方法二

這邊假設你已經裝了 Angular Cli

npm 安裝 jQuery

npm install jquery --save
npm install --save-dev @types/jquery

angular-cli.json 找到 "scripts": []

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

接著在你的 Component 裡面加上

import * as $ from 'jquery';

來測試看看

ng build
或
ng serve

這樣就大功告成了。

Enjoy Youself :)


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0
LeeBoy
iT邦新手 4 級 ‧ 2018-01-25 16:47:22

請問兩種方式有沒有差別,比如說用第二種 webpack 會計算引用數幫忙優化之類的

微中子 iT邦新手 4 級 ‧ 2018-01-28 23:59:19 檢舉

第一種直接引入的話,如果有採用 CDN,那下載速度會比較快
第二種我不確定 webpack 會有哪些優化耶

我要留言

立即登入留言