Search code examples
angulartypescriptflatpickr

Implementing a ControlValueAccessor but it's not propagating the value to the form


I am playing with the reactive forms on Angular, but I'm having troubles on propagating changes to the form from custom components.

For example, you can see in the plunkr a date-input component made with flatpickr.

https://plnkr.co/edit/okIjPb6aUcrzx3t7edae?p=info

you can see this piece of code in particular, that when it sets the property date it should propagate change to the form outside, but no, the form is not being updated.

ngOnInit() {
 this.instance = flatpickr(this.elDate.nativeElement, {
   onChange: (selectedDates, dateStr, instance) => {
     this.date = selectedDates[0];
   }
 });
}
set date(val) {
    this._date = val;
    this.propagateChange(val);
}

There's also a counter-input example in the plunkr, which works with angular native events and it works perfectly.

But in the date-input, which uses custom events (I presume) it doesn't work.

I supposed that the solution is something like the old applyAsync in the old Angularjs, but Angular promised to fix these issues by using zones, so something is not clear to me. I want an enlightment on the issue.


Solution

  • You forgot to bind your control to your FormGroup:

    <date-input [date]="date" formControlName="date"></date-input>
                              ^^^^^^^^^^^^^^^^^^^
                                  add this
    

    Forked Plunker