-1

Script/Jquery: I can't use this code for angular 2. How to use this script in angular 2? Or share me a link with examples.

    $(document).ready(function () {
        var data_input=$('input[name="date"]');
        var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent():"body";
        data_input.datepicker({
            format: 'mm/dd/yyyy',
            container: container,
            todayHighlight: true,
            autoclose: true,
        })
    })
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
<link rel="stylesheet" href="https://formden.com/static/cdn/bootstrap-iso.css" /> 

<link rel="stylesheet" href="https://formden.com/static/cdn/font-awesome/4.4.0/css/font-awesome.min.css" />

<div class="bootstrap-iso">
 <div class="container-fluid">
  <div class="row">
   <div class="col-md-6 col-sm-6 col-xs-12">
    <form method="post">
     <div class="form-group ">
      <label class="control-label " for="date">
       Date
      </label>
      <div class="input-group">
       <div class="input-group-addon">
        <i class="fa fa-calendar">
        </i>
       </div>
       <input class="form-control" id="date" name="date" placeholder="MM/DD/YYYY" type="text"/>
      </div>
     </div>
     <div class="form-group">
      <div>
       <button class="btn btn-primary " name="submit" type="submit">
        Submit
       </button>
      </div>
     </div>
    </form>
   </div>
  </div>
 </div>
</div>

this code only works in normal mode. it will't works in angular2.plz help me to solve this problem

    $(document).ready(function () {
        var data_input=$('input[name="date"]');
        var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent():"body";
        data_input.datepicker({
            format: 'mm/dd/yyyy',
            container: container,
            todayHighlight: true,
            autoclose: true,
        })
    })

HTML

<div class="bootstrap-iso">
 <div class="container-fluid">
  <div class="row">
   <div class="col-md-6 col-sm-6 col-xs-12">
    <form method="post">
     <div class="form-group ">
      <label class="control-label " for="date">
       Date
      </label>
      <div class="input-group">
       <div class="input-group-addon">
        <i class="fa fa-calendar">
        </i>
       </div>
       <input class="form-control" id="date" name="date" placeholder="MM/DD/YYYY" type="text"/>
      </div>
     </div>
     <div class="form-group">
      <div>
       <button class="btn btn-primary " name="submit" type="submit">
        Submit
       </button>
      </div>
     </div>
    </form>
   </div>
  </div>
 </div>
</div>
SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
byogesh
  • 1
  • 1

2 Answers2

2

You shouldn't run jquery/other plugins outside angular/angular2 rendering pipeline. Possible solutions are:

  1. use existing angualr2 component libraries (https://valor-software.com/ng2-bootstrap/#datepicker, http://www.primefaces.org/primeng/, or any vendor's plugins)
  2. create your own component, something similar to:

    import { Component, Input, Output, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
    import { ViewChild, EventEmitter, ElementRef } from '@angular/core';
    @Component({
       selector: 'date-time-picker',
       template: '<input #input type="text" class="form-control" />' 
    })
    export class DatetimePickerComponent implements AfterViewInit {
       @ViewChild('input') input:ElementRef;
       ngAfterViewInit() { //only here you are sure that html is available.
           $(this.input.nativeElement).datepicker({
              format: 'mm/dd/yyyy',
              container: container,
              todayHighlight: true,
              autoclose: true 
           });
       }
    }
    

    and use it everywhere in your app:

    <date-time-picker />
    

    maybe you are also interested in EventEmitter, to catch changes of the selected value.

if needed: this is the full code of directive I wrote to use http://eonasdan.github.io/bootstrap-datetimepicker/ and two way data binding in angular2 app:

    import { Component, Input, Output, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
    import { ViewChild, EventEmitter, ElementRef } from '@angular/core';
    import { ControlValueAccessor, NgControl } from '@angular/common';
    import * as moment from 'moment';

    declare var $: JQueryStatic;

    //http://eonasdan.github.io/bootstrap-datetimepicker/

    @Component({
        //moduleId: module.id,
        selector: 'date-time-picker',
        template: '<input #input type="text" class="form-control" />'
    })
    export class DatetimePickerComponent implements ControlValueAccessor, OnInit, AfterViewInit, OnDestroy {

        @Input('view-mode') viewMode: string;
        @Input('view-format') viewFormat: string;

        @Input('ngModel') ngModel:Date;
        @Output('ngModelChanged') ngModelChanged:EventEmitter<Date>;

        private ngModelChangeCallback:(Date)=>void;
        private ngModelTouchedCallback:Function;

        private jqueryObject: any;

        @ViewChild('input') input:ElementRef;

        constructor(private ctrl: NgControl) { 
            this.ctrl.valueAccessor = this;
            this.ngModelChanged = new EventEmitter<Date>();
        }

        ngAfterViewInit() { 
            let jElement:any =  $(this.input.nativeElement);

            this.jqueryObject = jElement.datetimepicker({
                viewMode: this.viewMode,
                format: this.viewFormat,
                defaultDate: this.ngModel
            });

            this.jqueryObject.on("dp.change", (e:any) => {
                //this.ngModelChange.emit(e.date.toDate());
                this.ngModelChangeCallback(e.date);
                this.ngModelChanged.emit(e.date);
            });
            this.jqueryObject.on("dp.show", (e:any) => {
                this.ngModelTouchedCallback(e.date);
            });

        }

        ngOnInit() {

        }

        ngOnDestroy() {
            if(this.jqueryObject) {
                $(this.jqueryObject).data("DateTimePicker").destroy();
            }
        }

        writeValue(date:Date) {
            if(!this.ngModel && !date) //no changes
                return;

            if(!moment(this.ngModel).isSame(date)) {
                this.ngModel = date; 

                if(this.jqueryObject) {
                    $(this.jqueryObject).data("DateTimePicker").date(this.ngModel);
                }
            }
        }

        registerOnChange(fn: (Date)=>void) {
            this.ngModelChangeCallback = fn;
        }

        registerOnTouched(fn: Function){
            this.ngModelTouchedCallback=fn;
        }
    }

to use in other components as:

  <date-time-picker [(ngModel)]="selectedDate" (ngModelChanged)="selectedMonthChanged($event)" view-mode='years' view-format='MM/YYYY'></date-time-picker>
Sierrodc
  • 845
  • 6
  • 18
  • thanks for your reply.but is shows an error , "Class 'DatePickerComponent' incorrectly implements interface 'On Destroy'. Property 'ngOnDestroy' is missing in type 'DatePickeComponent'. – byogesh Jun 06 '16 at 11:55
  • I've edited it removed interfaces not implemented + added full code of the directive. I don't know if I've followed the best practices, happy to receive suggestions. – Sierrodc Jun 06 '16 at 12:15
0

I believe that you need a new entry point to your JS code when using Angular 2.

See Angular2 equivalent of $document.ready()

I don't think that you can easily just run your Bootstrap/Jquery code in Angular2 without porting stuff. Are you using https://valor-software.com/ng2-bootstrap/ ?

Community
  • 1
  • 1
Peter Scott
  • 1,318
  • 12
  • 19