A Component's EventEmitter
does fire in some cases but does not in other cases. Why?
I have a custom Date picker. You can change the date manually (<input>
) or use ng2-bootstrap <datepicker>
to select conveniently.
I have this template:
<input [(ngModel)]="dateString"
class="form-control"
(focus)="showPopup()"
(change)="inputChange()">
<datepicker class="popup" [ngClass]="{ 'popup-hidden': !showDatepicker }"
[(ngModel)]="dateModel"
[showWeeks]="true"
(ngModelChange)="hidePopup($event)">
</datepicker>
The component with the relevant parts:
export class CustomDatepickerComponent {
@Input()
dateModel: Date;
dateString: string;
showDatepicker = false;
@Output()
dateModelChange: EventEmitter<Date> = new EventEmitter();
showPopup() {
this.showDatepicker = true;
}
// Called when the date is changed manually
// It DOES fire the event
inputChange() {
let result = moment(this.dateString, 'YYYY-MM-DD');
this.update(result.toDate());
}
// Called through the DatePicker of ng-bootstrap
// It DOESN'T fire the event
// However, the showDatepicker binding takes effect (see template)
hidePopup(event: Date) {
showDatepicker = false;
this.update(event);
}
update(date: Date) {
this.dateModel = date;
this.dateString = moment(date).format('YYYY-MM-DD');
// This SHOULD fire the event
// It is called in BOTH cases!
// But it fires only when the date is changed through the <input>
this.dateModelChange.emit(this.dateModel);
}
I use this datepicker this way:
<custom-datepicker [dateModel]="testDate" (change)="change($event)"></custom-datepicker>
Here's the change()
handler function.
testDate = new Date();
change($event) { console.info('CHANGE', $event); }
Any ideas?
Ok... Now this is somewhat embarassing. This was the usage of this component:
Which should be changed to:
The interesting part is that it seems that the
changed
event of the<input>
element bubbled up fromCustomDatepickerComponent
. It was handled inside the component, it fireddateModelChange
which was not handled, then it bubbled up to the outer component aschange
event -- and this way it was handled.If I passed the event to
inputChange()
and calledevent.stopPropagation()
then it was cancelled and did not propagate.Once again: it was nothing to do with
EventEmitter
.