angular2 uses custom instruction (Directive) to load jquery plug in

  • 2021-07-18 06:50:09
  • OfStack

Since angular 2 has not been around for a long time, there are still few related plug-ins, so it is sometimes necessary to use a few jquery plug-ins to complete the project.

So how do you put the jquery plug-in into angular2? Adopt custom instructions!

jquery is introduced before the context, which is not described anymore

First, create a directive and use @ input to get the parameters required by jquery plug-in.

Initializes the jquery plug-in at ngOnChanges, when the parameter is passed in via @ input,

To initialize the jquery plug-in, we need to get the dom element, so we introduce ElementRef to get the dom element

Here, we need to talk about the callback function in jquery. If we use this directly, the callback can't get the function of angular

So here we take the form of bind and pass this in. In this way, the function in angular will be called correctly.

The following is the code to implement the time plug-in:


import { Directive, Output, Input, ElementRef, EventEmitter } from '@angular/core';

//  Introduce jquery.daterangepicker Plug-in correlation JS And css,Css When packaging, you need to package it into a single file, or directly in the html Separate reference 
//  How to package individually see the code in the following section 

require('../../../../assets/lib/bootstrap-daterangepicker-master/daterangepicker.js');
require('../../../../assets/lib/bootstrap-daterangepicker-master/daterangepicker.css');

//  Custom instruction 
@Directive({
 selector: '[dateRangePicker]',
})

export class DateRangePicker {

 /**
  * jquery.daterangepicker Parameters required by plug-in 
  *  Parameter :http://www.daterangepicker.com/#options
  */
 @Input() public dateRangePickerOptions: IJQueryDateRangePicker;

 //  Selected event 
 @Output() selected: any = new EventEmitter();

 /**
  *  Initialization 
  * @param _elementRef
  */
 constructor(private _elementRef: ElementRef) {
 }

 /**
  *  Property changes 
  * @private
  */
 ngOnChanges() {
  $(this._elementRef.nativeElement).daterangepicker(this.dateRangePickerOptions, this.dateCallback.bind(this));
 }

 /**
  *  Use when the time changes emit Passing Events 
  * @private
  */
 dateCallback(start, end) {
  let format = "YYYY-MM-DD";
  if (this.dateRangePickerOptions.locale.format) {
   format = this.dateRangePickerOptions.locale.format;
  }
  let date = {
   startDate: start.format(format),
   endDate: end.format(format),
  }

  this.selected.emit(date);
 }

}


import { Component } from '@angular/core';
import { DateRangePicker } from '../../theme/directives';


@Component({
 selector: 'dashboard',
 template: `
   <div class="form-group">
        <label for="startDate">{date.startDate}</label>
        <input 
        dateRangePicker 
        [dateRangePickerOptions]="option"    
        (selected)="dateSelected($event)" 
        type="text" 
        class="form-control">
   </div>
 `,
 directives: [DateRangePicker]
})
export class Dashboard {

 /**
  *  The currently selected time 
  */
 public date: any

 /**
  * jquery Time plug-in parameters 
  */
 private option: Object = {
  locale: {
   format: "YYYY-MM-DD",
   separator: "  To  ",
   applyLabel: " Determine ",
   cancelLabel: ' Cancel ',
   fromLabel: ' Start time ',
   toLabel: ' End time ',
   customRangeLabel: ' Customize ',
   daysOfWeek: [' Day ', '1', '2', '3', '4', '5', '6'],
   monthNames: ['1 Month ', '2 Month ', '3 Month ', '4 Month ', '5 Month ', '6 Month ',
    '7 Month ', '8 Month ', '9 Month ', '10 Month ', '101 Month ', '102 Month '],
   firstDay: 1
  },
 };

 constructor() {
 }

 /**
  * emit Callback event to get the selected time 
  * @param date
  */
 dateSelected(date) {
  this.date = date;
 }
}

Also note that css needs to be packaged separately, or html needs to be referenced separately. How to package css, please see the end. I packaged it with webpack here


//  Adopt ExtractTextPlugin Individual pair jquery Plug-in css Packing 
loaders: [{
    test: /daterangepicker\.css$/,
    loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
   }]

plugins: [
     new ExtractTextPlugin('[name].css', {
      allChunks: true
     })]


Related articles: