自动完成 matInput 中的两种方式数据绑定

Two way databinding within Autocomplete matInput

我正在使用 material 自动完成输入从数据库中搜索文章,我正在使用 table 列中的普通输入和用于双向数据绑定的 ngModel 指令,并且想要将此输入更改为自动完成输入,因此我在文档中提到 Angular 添加了输入中的 formControl,这样我就可以订阅组件中的 valueChanges

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)
    ));

自动完成工作正常,每当输入值发生变化时调用我的 Rest web 服务,用户可以选择他的文章并提交以保存在我的数据库中,那么问题就在这里:无法正确绑定输入视图我选择的文章从数据库中收到,知道没有自动完成输入和 formControl 的需要,ngModel 可以很好地完成绑定工作所以我的问题是:是否有解决方案如何订阅 ngModel 上的值更改?所以我可以在这里替换 [formControl] 实用程序,因为我知道 ngModel 和 formControl 的使用已被弃用 https://angular.io/api/forms/FormControlDirective#use-with-ngmodel

您可以摆脱 [FormControl] 并使用触发输入更改的 (ngModelChange)。它看起来像那样

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

在你的打字稿中,你的搜索函数从后端获取值:

searchFunction() {//Code here }

这是一个显示 NgModelChange 功能的 stackblitz https://stackblitz.com/edit/angular-wzw7by