angular2怎么使用第三方的库?jquery等

网上找了很多教材都搜索不到该部分类型,自己测试了下写了该教程。

场景说明:项目需要使用bootstrap,众所周知bootstrap没有时间日期控件的,需要使用第三方控件,我对如何在angular2中使用第三方控件比较恐慌,我项目使用angular-cli构建的。

解决流程

1:配置package.json添加新的依赖,然后进行update,下载新的库

  1. "jquery":"*",
  2. "tether":"*",
  3. "bootstrap":"*",
  4. "moment":"*",
  5. "eonasdan-bootstrap-datetimepicker":"*"

2: 配置angular-cli.json

  1. "styles": [
  2. "../node_modules/bootstrap/dist/css/bootstrap.min.css",
  3. "../node_modules/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css",
  4. "styles.css"
  5. ],
  6. "scripts": [
  7. "../node_modules/jquery/dist/jquery.min.js",
  8. "../node_modules/tether/dist/js/tether.min.js",
  9. "../node_modules/bootstrap/dist/js/bootstrap.min.js",
  10. "../node_modules/moment/min/moment.min.js",
  11. "../node_modules/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js"
  12. ],

3: 在模版中使用datatimepicker插件

  1. <div class="container">
  2. <div class="row">
  3. <div class='col-sm-6'>
  4. <div class="form-group">
  5. <div class='input-group date' >
  6. <input type='text' class="form-control" />
  7. <span class="input-group-addon">
  8. <span class="glyphicon glyphicon-calendar"></span>
  9. </span>
  10. </div>
  11. </div>
  12. </div>
  13. </div>
  14. </div>

4:在组件中对该组件进行实例化

  1. declare var $:any;
  2. @Component({
  3. selector:"app-root",
  4. templateUrl:"bootstrap.template.html"
  5. })
  6. export class BootstrapComponent extends OnInit{
  7. ngOnInit(): void {
  8. $(function () {
  9. $('#datetimepicker1').datetimepicker();
  10. });
  11. }
  12. }

这里注意需要声明$变量,如果你使用jquery那么声明jquery变量,如果不声明,console会有提示错误,这里的声明为什么会起作用我具体也不是很清楚,也许类似d.ts的作用吧。

来自为知笔记(Wiz)