0

I tried to write the below code in ngOnInit


$('#DatePicker').datepicker({
          changeMonth: true,
          changeYear: true,
          maxDate:0,
          //The calendar is recreated OnSelect for inline calendar
          onSelect: function(date, dp) {
            this.updateDatePickerCells(dp);

          },
          onChangeMonthYear: function(month, year, dp) {
            this.updateDatePickerCells(dp);
          },
          beforeShow: function(elem, dp) { //This is for non-inline datepicker
            this.updateDatePickerCells(dp);
          }
        });

updateDatePickerCells(dp) {
    /* Wait until current callstack is finished so the datepicker
       is fully rendered before attempting to modify contents */
    setTimeout(function() {
      //Fill this with the data you want to insert (I use and AJAX request).  Key is day of month
      //NOTE* watch out for CSS special characters in the value
      var cellContents = {
        '15-06-2020': '20',
        '15-08-2018': '60',
        '28-08-2018': '$99.99'
      };
      //Get the month and year for checking.
      var selected_month = parseInt($('.ui-datepicker-month').val()) + 1;
      var selected_year = $('.ui-datepicker-year').val();
      //Select disabled days (span) for proper indexing but // apply the rule only to enabled days(a)
      $('.ui-datepicker td > *').each(function(idx, elem) {
        //Specific the target key by adding back the month and year.
        var key = ('0' + (idx + 1)).slice(-2) + '-' + ('0' + selected_month).slice(-2) + '-' + selected_year
        var value = cellContents[key] || 0;

        // dynamically create a css rule to add the contents //with the :after                         
        //             selector so we don't break the datepicker //functionality 
        var className = 'datepicker-content-' + CryptoJS.MD5(value).toString();


        if (value == 0)
          this.addCSSRule('.ui-datepicker td a.' + className + ':after {content: "\\a0";}'); // 
        else
          this.addCSSRule('.ui-datepicker td a.' + className + ':after {content: "' + value + '";}');

        $(this).addClass(className);


      });
    }, 0);
  }
   dynamicCSSRules = [];

   addCSSRule(rule) {
    if ($.inArray(rule,this.dynamicCSSRules) == -1) {
      $('head').append('<style>' + rule + '</style>');
      this.dynamicCSSRules.push(rule);

    }
  }

Update method is used to display some content on calendar cell based on date. Also imported the below script file and css file in index.html

 <script src="./assets/jquery-ui.js"></script>
  <link rel="stylesheet"  href="./assets/jquery-ui.css">

Getting the following error

ERROR TypeError: jquery__WEBPACK_IMPORTED_MODULE_0__(...).datepicker is not a function
    at CalendarComponent.ngOnInit (calendar.component.ts:16)
    at checkAndUpdateDirectiveInline (core.js:33353)
    at checkAndUpdateNodeInline (core.js:46284)
    at checkAndUpdateNode (core.js:46223)
    at debugCheckAndUpdateNode (core.js:47246)
    at debugCheckDirectivesFn (core.js:47189)
    at Object.updateDirectives (calendar.component.html:1)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:47177)
    at checkAndUpdateView (core.js:46188)
    at callViewAction (core.js:46554)

Please anyone suggest me how to use Jquery datepicker in angular or any another way on how to add extra text to calendar cell based on date...

Thanks in Advance!!!

2 Answers 2

1

I would NOT recommend to use direct DOM editing libraries like JQuery, it is considered bad pratice as it can interfere with the way Angular modifies DOM causing Bugs.

Instead you can use Angular Bootstrap which is implemented without JQuery. Or Angular Meterial.

However if you insist on using JQuery you could try other lifecycle hooks [3]

[1] https://ng-bootstrap.github.io/#/components/datepicker/examples

[2] https://ng-bootstrap.github.io/#/home

[3] https://angular.io/guide/lifecycle-hooks

Sign up to request clarification or add additional context in comments.

2 Comments

But the thing is that I need to display some value on the date cell based on the date... can we achieve that if we use the above
You need to describe what you are trying to do in more detail. Please do this by editing your Question.
0

Keep in mind that is it considered bad practice to use jQuery with angular, either wrap the logic in a directive or use an existing alternative. If for instance you are using bootstrap datepicker, there's already written a ton of directives wrapping jquery for you :-) (eg. https://www.npmjs.com/package/ngx-date-picker)

Otherwise you can inject ElementRef in the constructor like so.

declare var $: any; 
// compiler will no longer complain, 
// but a more typesafe way would be to install jquery with typescript definitions

export class MyComponent {
  constructor(private elRef:ElementRef) {}
  ngAfterViewInit() {
    var div = this.elRef.nativeElement.querySelector('div');
    console.log(div);
  }

  ngAfterContentInit() {
    var div = this.elRef.nativeElement.querySelector('div');
    // Do jquery binding inside here. 
    console.log(div);
  }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.