0

Hi I am upgrading an application to angular 2. I am creating a new datepicker component, wrapping a vanilla javascript datepicker (pikaday) The component looks great, but when I select a date, I can't see those changes in my angular model.

constructor(myInput: ElementRef) {
        let opts = {
            field: myInput.nativeElement,
            format:  'YYYY-MM-DD',
            onSelect: () => {
                this.value = this.datePicker.getMoment().format(this.dateFormat);
            }
        };
        this.datePicker = new Pikaday(opts);
    }
<!---- template --->

<div class="cad-date-picker field">
    <label class="field__in el-w100">
        <input class="input" value="{{value}}" readOnly/>
        <div class="field__icon">
                <cad-icon name="calendar"></cad-icon>
        </div>
    </label>
</div>

----------------------------------------

<!---- Page --->
<div class="field">
  <label class="field__in el-w100">
     <input class="input" name="startDate" cad-date-time-picker="vm.startDateOptions" ng-required="vm.isSubmitting" ng-model="vm.rfp.startDate" ng-model-options="{allowInvalid: false}" ng-change="vm.dateChange('startDate')"/>
      <div class="field__icon">
        <cad-icon name="calendar"></cad-icon>
       </div>
   </label>
</div>
                
<cad-date-picker [(value)]="vm.rfp.startDate"></cad-date-picker>

In am testing with the two components, the up component is angular 1, the down component is angular 2.

enter image description here

I already tried to do this post, but it does not work

Community
  • 1
  • 1
dobleUber
  • 566
  • 6
  • 22

1 Answers1

2

You should be aware of two-way binding in Angular is done by EventEmitter, take as reference Toughtram's
post https://blog.thoughtram.io/angular/2016/10/13/two-way-data-binding-in-angular-2.html

@Component({
         selector: 'my-date-picker',
         template: `<div class="my-date-picker field">
<label class="field__in el-w100">
    <input #myDateInput class="input" [(ngModel)]="value" readOnly/>
    <div class="field__icon">
            <my-icon name="calendar"></cad-icon>
    </div>
</label>`,
         styles: [require('./date-picker.scss')],
         encapsulation: ViewEncapsulation.None
       })
export class DatePickerComponent implements OnInit {
  @ViewChild('myDateInput') myInput: ElementRef;
  @Input() dateFormat = 'YYYY-MM-DD';

  @Input() get value() {
    return this._value;
  }

  @Output() valueChange = new EventEmitter();
  set value(newVal: string) {
    this._value = newVal;
    this.valueChange.emit(this._value);
  }

  private datePicker: any;
  private _value: string;

  ngOnInit() {
    let opts = {
      field: this.myInput.nativeElement,
      format: this.dateFormat,
      onSelect: () => {
        this.value = 
this.datePicker.getMoment().format(this.dateFormat);
      }
    };
    this.datePicker = new Pikaday(opts);
  }
}

That way, you could handle the value from outside...