【问题标题】:how to get the selected value <mat-select> from HTML into ts file?如何将选定的值 <mat-select> 从 HTML 获取到 ts 文件中?
【发布时间】:2019-09-19 15:39:11
【问题描述】:

我正在尝试将选定的值从 HTML 获取到 ts 文件中。下面是使用 Angular 材质标签的 HTML 代码

      <mat-form-field [style.visibility]="visibility" >
              <mat-label>Apps</mat-label>
              <mat-select #selectedApp (change)='fetchTableData($event)'>
                    <mat-option *ngFor="let apps of appsList$" [value]="apps.appName">{{apps.appName}}</mat-option>
                    <mat-option [value]="all">All</mat-option>
              </mat-select>
        </mat-form-field>

.ts 代码

     @ViewChild('selectedApp') selectedApp;

     ngOnInit() {             
             return this.testcaseService.getAll()
         .subscribe(apps => this.appsList$ = apps);

      }

     fetchTableData(event: any){                  

        console.log("Selected App: "+this.selectedApp.Selected);
      } 

我不确定我在这里做错了什么。谁能帮帮我

【问题讨论】:

    标签: angular


    【解决方案1】:

    将您的 (change) 事件更改为 fetchTableData($event.value)

     <mat-form-field [style.visibility]="visibility" >
                  <mat-label>Apps</mat-label>
                  <mat-select #selectedApp (change)='fetchTableData($event.value)'>
                        <mat-option *ngFor="let apps of appsList$" [value]="apps.appName">{{apps.appName}}</mat-option>
                        <mat-option [value]="all">All</mat-option>
                  </mat-select>
     </mat-form-field>
    

    并将事件用作选定值

    fetchTableData(event: any) {
    
        console.log("Selected App: " + event);
      }
    

    演示https://stackblitz.com/edit/angular-mat-select-data-2

    你不应该使用this.selectedApp.Selected

    【讨论】:

    • 我已经尝试了上述解决方案。它不工作,还有其他问题吗?
    • 谢谢。我检查了你的代码,它看起来非常好。但不知何故,它在我当地不起作用。当我从下拉更改选项时,控件不会进入 ts 中的 fetchTableData(event) 。我在控制台或任何我可以调试的东西中都没有收到任何错误。奇怪。
    【解决方案2】:

    我认为您需要使用 mat-select 中的 selectionChange 事件绑定。

    https://material.angular.io/components/select/api

    【讨论】:

    • 谢谢。我已遵循您的建议和此解决方案 -stackoverflow.com/questions/50614991/…,但这也不适用于我。我想知道我在这里做错了什么?
    • 你用的是什么版本的角材料?
    • "@angular/cli": "~7.3.8"
    • 感谢 Prasanth,我已将 (change) 修改为 (selectionChange),它现在工作得很好。 Google 似乎从 angular 6 更改了语法。
    猜你喜欢
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    相关资源
    最近更新 更多