Search code examples
angularautocompleteform-controltwo-way-binding

Two way databinding within Autocomplete matInput


I'm using a material autocomplete input to search an article from a database, i was working with a normal input in a table column with ngModel directive for two-way databinding and wanted to change this input to an autocomplete input so i added as Angular mentionned in documentation a formControl in the input so i can subscribe to valueChanges in the Component

Template

<tbody>
 <tr *ngFor="let ligneFacture of facture.lignesFacture; let i =index;">
  <td>
    <form>
      <mat-form-field >
         <input type="text" class="form-control" matInput [formControl]="articleKeyword"
           [matAutocomplete]="auto [(ngModel)]="ligneFacture.articleId">
         <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn.bind(this)">
           <mat-option *ngFor="let article of articles;" [value]="article.id">
              {{article.libelle}}
           </mat-option>
         </mat-autocomplete>
      </mat-form-field>
    </form>
  </td>

TypeScript

articleKeyword = new FormControl();

ngOnInit() {
  //some code here 

         this.articleKeyword.valueChanges.subscribe(value => this.articleService.queryByKeyword(value).subscribe(
        (res: HttpResponse<IArticle[]>) => {
            this.articles = res.body;
        },
        (res: HttpErrorResponse) => this.onError(res.message)
    ));

The Autocomplete works fine and call my Rest webservice whenever the value of the input changes and the user can choose his article and submit to save in my database then the problem is here : cant bind correctly the view of the input with my choosen articles recieved from database knowing that without the autocomplete input and the need for formControl , ngModel was working fine to do the binding work so my question here : is there a solution how to subscribe for valuechanges on ngModel ? so i can replace the [formControl] utility here knowing that the use of both ngModel and formControl is deprecated in as mentionned here https://angular.io/api/forms/FormControlDirective#use-with-ngmodel


Solution

  • You can get rid of the [FormControl] and use insted the (ngModelChange) who fires the change of your input. it would look something like that

     <input type="text" matInput (ngModelChange)='searchFunction($event)'
           [matAutocomplete]="auto [(ngModel)]="ligneFacture.articleId">
    

    and in your typescript your search function that gets the values from the back end:

    searchFunction() {//Code here }
    

    Here is a stackblitz showing the functionning of the NgModelChange https://stackblitz.com/edit/angular-wzw7by