Angular 10 input value binding changed by jquery.val()

Viewed 520

I'm using bootstrap-autocomplete, but the bound model is not updated when selecting a value.

I looked into the bootstrap-autocomplete source code, and it is using JQuery.val() to assign a selected value, and it looks like if JQuery.val() is used, the model is not updated.

-- template
<input id="test" class="form-control" type="text" autocomplete="off" [(ngModel)]="myValue">
Angular Model: {{myValue}}
<br />
Jquery Val: {{getJqueryValue()}}


-- component
import { Component, AfterViewInit } from '@angular/core';
import 'bootstrap-autocomplete'
declare const $: any;
@Component({
  selector: 'app-app-list',
  templateUrl: './app-list.component.html',
  styleUrls: ['./app-list.component.css']
})
export class AppListComponent implements AfterViewInit {
  public myValue: string;
  ngAfterViewInit(): void {
    $('#test').autoComplete({
      resolver: 'custom',
      events: {
        search: function (qry, callback) {
          callback(["google", "yahoo", "amazon"])
        }
      }
    });
  }
  getJqueryValue() {
    return $('#test').val();
  }
}

enter image description here

How can I make Angular to understand that the value is changed?

FYI, I cannot use Angular material or other angular compatible autocomplete.

https://stackblitz.com/edit/angular-playground-6dpemy?file=app%2Fapp.component.ts

2 Answers

Using your StackBlitz as a reference I was able to build this solution:

Template

<!--   | Add a template reference so you can grab this element from your component. -->
<!--   v Name it what ever you like. -->
<input #test id="test" class="form-control" type="text" autocomplete="off" [(ngModel)]="myValue">

Component

export class YourComponent implements AfterViewInit {
    public myValue: string;
    @ViewChild('test') test: ElementRef; // <- The name in quotes must match on the template

     ngAfterViewInit(): void {
         $('#test').autoComplete({
             resolver: 'custom',
             events: {
                 search: function (qry, callback) {
                     callback(["google", "yahoo", "amazon"])
                 }
             }
          });
          $('#test').on('autocomplete.select', (ev, item) => {              
              this.test.nativeElement.dispatchEvent(
                  new CustomEvent('input', { bubbles: true })
              );
          });
     }
}

Demo https://stackblitz.com/edit/angular-playground-r3s5b3?file=app/app.component.ts

Related