【问题标题】:Angular - HTML - pass selected value from drop down to TS method on button clickAngular - HTML - 在按钮单击时将选定值从下拉列表传递到 TS 方法
【发布时间】:2022-01-05 10:20:48
【问题描述】:

我遇到的问题是我无法访问 {{selectItem}} 中的 .value 和 .id 以将它们发送回打字稿以便稍后发布 HTTP 帖子。虽然没有实际的错误,但我有例外,并且已经用谷歌搜索解决但无济于事。

抛出异常:System.Net.Sockets.dll 中的“System.IO.IOException” 抛出异常:System.Private.CoreLib.dll 中的“System.IO.IOException” 抛出异常:System.Net.Http.dll 中的“System.Threading.Tasks.TaskCanceledException” 抛出异常:System.Private.CoreLib.dll 中的“System.Threading.Tasks.TaskCanceledException” 抛出异常:System.Private.CoreLib.dll 中的“System.Threading.Tasks.TaskCanceledException”

我了解 {{selectedItem | json}} 只是将所选项目放入 JSON 表单,但我想简单地将 .id 和 .values 传递回按钮单击的方法。挣扎了一周左右。任何指导表示赞赏。

<div div class="main-search-user-name">
        <mat-form-field>
          <mat-label>Search Select User</mat-label>
          <mat-select [(ngModel)]="selectedItem">
            <mat-option *ngFor="let getddusers of getusers" [id]="getddusers.id" [value]="getddusers.value">
              {{getddusers.id}} {{getddusers.value}}
            </mat-option>
          </mat-select>
        </mat-form-field>
        {{selectedItem | json}}
        <button type="button" class="btn btn-primary btn-sm">Search</button>
        <button type="button" class="btn btn-primary btn-sm" (click)="displayName('{{getddusers.id}}' + '{{getddusers.value}}')">Search</button>
</div>

【问题讨论】:

  • (click)="displayName('getddusers.id' + 'getddusers.value')"

标签: html angular typescript collections data-binding


【解决方案1】:

您需要将属性绑定从 [value]="getddusers.value" 更改为 [value]="getddusers"

这样做将确保selectedItem 代表整个对象,然后您可以在组件ts 文件中的displayName() 中简单地使用this.selectedItem.idthis.selectedItem.value

【讨论】:

  • 完美运行。谢谢:)
【解决方案2】:

您可以在组件的displayName() 方法中使用selectedItem 变量。由于您在ngModel 中使用selectedItem,它将在组件中更新 即

//app.component.ts

export class AppComponent {
  selectedItem: any= null;
  
  displayName(){
     //you can use selectedItem here
    console.log("Selected user"+ this.selectedItem.id);
  }

}

【讨论】:

  • 感谢 Borad,虽然这有所帮助,但在 displayName() 方法中使用 .id 或 .value 时,我会在控制台窗口中收到“未定义”警报。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 2012-12-13
  • 2019-02-07
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多