【问题标题】:Two way databinding within Autocomplete matInput自动完成 matInput 中的两种方式数据绑定
【发布时间】:2019-02-21 12:23:37
【问题描述】:

我正在使用材料自动完成输入从数据库中搜索文章,我正在使用带有 ngModel 指令的表列中的正常输入进行双向数据绑定,并希望将此输入更改为自动完成输入,所以我在文档中添加了作为 Angular 提及的输入中的 formControl,以便我可以订阅组件中的 valueChanges

模板

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

打字稿

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 上的 valuechanges?所以我可以在这里替换 [formControl] 实用程序,因为这里提到的 ngModel 和 formControl 已被弃用 https://angular.io/api/forms/FormControlDirective#use-with-ngmodel

【问题讨论】:

    标签: angular autocomplete form-control two-way-binding


    【解决方案1】:

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

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

    在你的打字稿中你的搜索功能从后端获取值:

    searchFunction() {//Code here }
    

    这是一个堆栈闪电战,展示了 NgModelChange 的功能 https://stackblitz.com/edit/angular-wzw7by

    【讨论】:

    • 我在 TS 中添加了该函数,并将其传递给输入中的 ngModelChange,就像您提到的那样,但从未调用此函数来触发我的输入更改,我尝试调试并且该函数仅调用一次组件构建时searchFunction(event: any) { this.articleService.queryByKeyword(event.target.value).subscribe( (res: HttpResponse&lt;IArticle[]&gt;) =&gt; { this.articles = res.body; }, (res: HttpErrorResponse) =&gt; this.onError(res.message) ); }
    • 你确定你用对了吗,你可以重新检查我的答案,有一个小的 stackblitz 解释了 NgModelChange 的行为,也许它可以帮助
    • 我在表单中使用了 ngModel 指令,所以我需要添加 [ngModelOptions]="{standalone: true}" 现在它可以正常工作了,谢谢
    猜你喜欢
    • 1970-01-01
    • 2019-03-09
    • 2016-02-27
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    相关资源
    最近更新 更多