1. 程式人生 > >angular6引入jquery和jquery外掛

angular6引入jquery和jquery外掛

文章參考

  1. Angular雜談系列1-如何在Angular2中使用jQuery及其外掛
  2. angular4引入jQuery和基於jQuery的外掛!

案例說明

一、angular-cli.json引入jquery和jquery外掛

"scripts": [
    "node_modules/jquery/dist/jquery.js",
    "src/assets/bootstrapvalidator/js/bootstrapValidator.min.js",
    "node_modules/datatables.net/js/jquery.dataTables.js"
]

二、在業務邏輯程式碼中

import {Component, OnInit, OnDestroy} from '@angular/core';
import {HttpInterceptorService} from '../../../utils/http-interceptor.service';
import {API_CONFIG} from '../../../config/apiConfig';
import { SERVER_CONFIG } from '../../../config/serverConfig';
import { SERVER_DATA } from '../../../config/data'
; import { BsModalService } from 'ngx-bootstrap/modal'; import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service'; import _ from 'lodash'; // 一定要宣告 $ 符,不然編譯會報錯, // 如果 import * as $ from 'jquery';這樣宣告則編譯會提示不識別 $('#searchForm').bootstrapValidator()這個方法,編譯依然不過 declare var $: any; @Component({ selector:
'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { public eventDetailObj = null; public http: HttpInterceptorService; public modalRef: BsModalRef; public modalService: BsModalService; // 建構函式,注入 HttpInterceptorService constructor (httpService: HttpInterceptorService, modalService: BsModalService) { this.http = httpService; this.modalService = modalService; } validFormAction () { $('#searchForm').bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { keyword: { message: 'The username is not valid', validators: { notEmpty: { message: 'please enter a key word.' } } }, userInputLocation: { message: 'The username is not valid', validators: { notEmpty: { message: 'please enter a location.' } } }, } }) // .on('success.form.bv', function(e) { // debugger // // 阻止預設事件提交 // e.preventDefault(); // }); $('#searchForm').submit(function(e){ e.preventDefault(); }); } ngOnInit() { this.validFormAction(); this.getUserLocation(); this.getLocationByAddress(); } }