Search code examples
datepickerangular6vmware-clarity

How to capture change of Clarity Date Picker


I am using the double-binding of the clrDate, which allows me to load a Javascript Date object. However, I need to trigger an event every time the user changes the date, either types in a new one or uses the calendar.

I've tried (click), (change), (ngModelChange), (blur) - but for some reason none of them seem to trigger.

<label for="modelDate" class="clr-control-label" >Model Date:</label>     
<input clrDate type="date" [(clrDate)]="selectedModelDate" (ngModelChange)="loadModel(false)" > 

How should I capture the change within the Date Picker?


Solution

  • You can do it in two ways.

    2-way Binding

    In this stackblitz, notice that before the date picker is interaced with, if you click the button then the value of date1 is undefined. After you select a date and click the button it has the value set in the date picker. This is typical 2-way binding in Angular.

    <section>
      <button class="btn btn-primary" (click)="logDate1()">
        Log Date Value for 2-way binding
      </button>
      <label for="date1" class="clr-control-label" > Date1:</label>     
      <input type="date" [(clrDate)]="date1" />
    </section> 
    

    De-sugarized Syntax

    This might be what you are after. It's almost the same as the above example but we seperate or de-sugarize the 2-way binding so that it gets set with [clrDate]=date2. Notice that it fires an event clrDateChange that can be tied into with the logChnage($event). That will get fired whenever the internal value of the date picker changes (e.g user selects a date) and you can do whatever you want with it's value in the logChange function. This is 2-way binding de-sugarized.

    <section>
      <h4>De-sugarized syntax</h4>
      <label for="date2" class="clr-control-label" > Date1:</label>     
      <input type="date" [clrDate]="date2" (clrDateChange)="logChange($event)"/>
    </section>