Update [(ngModel)] on jquery plugin event

Issue

Is there any way to refresh ngModel on jquery event e.g.

  1. datetimepicker on ‘dp.change’ event.
  2. Select2 on select change event.

Solution

We can do something like that. It works for me.

In html template

 <input type="text" class="form-control" [listItem]="list" autocomplete id="txtbox" name="txtbox" placeholder="myplaceholder" [(ngModel)]="myModel">

In typescript code

import { Directive, ElementRef, Input } from '@angular/core';
import { NgModel } from '@angular/forms';
declare var $;
@Directive({
  selector: '[ngModel][autocomplete]',
  providers: [NgModel]
})
export class Autocomplete {
  @Input() listItem: any = [];
  constructor(public _elementRef: ElementRef, private ngModel: NgModel) {
  }
  ngAfterViewInit() {
    let that = this;
    $(this._elementRef.nativeElement).typeahead({
      source: this.listItem.map(item => {
        return { id: item.account.toString(), name: item.account.toString() };
      })
    });

    this.ngModel.valueChanges.subscribe(function(value) {
      /* Set any value of your custom control */
      $(this._elementRef.nativeElement).data("newValue", value);
    });

    /* Inform ng model for any new change happened */
    $(this._elementRef.nativeElement).bind("change", ()=>{
      that.ngModel.update.emit($(that._elementRef.nativeElement).val());
    });
  }
}

Answered By – Mantu Nigam

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.