@api label;
uniqueId;
@track placeholder;
connectedCallback() {
// Increment the static variable to get a unique ID
unkDateInputId += 1;
// Set the unique ID property using the incremented value
this.uniqueId = `date-input-${unkDateInputId}`;
}
// Handle the date change and propagate the event to the parent component
handleDateChange(event)
{
const selectedDate = event.target.value;
// Dispatch a custom event to notify the parent
this.dispatchEvent(new CustomEvent('change', { detail: { value: selectedDate } }));
this.value = new Date(selectedDate);
this.formatDate();
}
formatDate() {
if (this.value instanceof Date ) //&& !isNaN(this.value))
{
const day = this.value.getDate().toString().padStart(2, '0');
const month = (this.value.getMonth() + 1).toString().padStart(2, '0');
const year = this.value.getFullYear().toString().slice(-2); // Get the last two digits
this.formattedDate = `${day}/${month}/${year}`;
console.log('Selected date ',this.formattedDate);
} else {
// Handle invalid date
this.formattedDate = ''; console.log('no date value');
}
// Dispatch a custom event to notify the parent
this.dispatchEvent(new CustomEvent('change', { detail: { value: this.formattedDate } }));
}
html
<label class="unkuk-label unkuk-date-input__label" for={date} if:true={label}>
{label}
</label>
<input
class="unkuk-input unkuk-date-input__input"
id={name}
name={uniqueId}
value={value}
placeholder="dd/mm/yy"
type="date"
onchange={handleDateChange}>
Trying to pass the label and Value to the parent is not working. Couldn't read date value in parent.
parent.html
<div class="unkuk-date-input">
<c-unk-date-input
data-form-element="enddate"
name="enddate"
label="End Date"
value ={model.enddate.value}
required
placeholder="dd/mm/yyyy"
onchange={handleFormFieldChange}>
</c-unk-date-input>
</div>
parent.js
@track model = {
enddate:{value:undefined,error:undefined}
};
handleFormFieldChange(event)
{
const field = event.detail?.fieldName;
//if (!field) return;
const value = event.detail?.value;
const error = event.detail?.error;
console.log('enddate' ,this.model.enddate);
}
handleFormFieldError(event)
{
this.handleFormFieldChange(event);
console.log('handleFormFieldError triggered:', event.detail);
//this.handleInvalidDate(event);
}