【问题标题】:Get bound object based on it's id根据 id 获取绑定对象
【发布时间】:2018-04-28 06:20:26
【问题描述】:

我有这个textbox 供客户搜索id

Enter Id: <input type="text" [(ngModel)]="temp.id"> 
<button (click)="myEvent()">My Button</button>

<table class='table' *ngIf="collection">
<tbody>
    <tr *ngFor="let item of collection">
        <td>{{ item.id }}</td>
        <td>{{ item.name }}</td>
    </tr>
</tbody>

myEvent方法中,我不知道我应该如何获取给定Id的相关绑定对象,以便我得到它的name属性并将其发送到我的WEB API:

temp: any = { id: '' };

myEvent() {
    this.http.get('url', {
        params: {
            id: this.temp.id,
            name: ???
        }
    })
}

【问题讨论】:

  • 在你的 *ngFor 循环中吗?
  • @RukshanDangalla 不。正如我在更新的问题中显示的那样,它不在表格之外。
  • @RukshanDangalla 如果解决方案是将我的按钮放在 *ngFor 循环中,我将更改我的代码。请告诉我我该怎么做?

标签: c# angular asp.net-web-api asp.net-core-mvc


【解决方案1】:

如果您有自己的收藏品,您可以通过id 属性通过多种方式找到该收藏品。

这是使用array find method的一种方法:

myEvent() {
    const item = this.collection.find(i => i.id === this.temp.id);

    if (!item) {
        return;
    }
    ...
}

【讨论】:

  • 谢谢。什么是 const 类型?为什么不应该是我的界面类型?
  • const 是类似 varlet 的关键字。它只是表示不应再次写入此变量。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 那么我应该如何从 const item 中获取名称?因为我的智能在它之后不起作用!这不起作用name:item.name,
  • 如果您添加检查以确保找到该项目,您应该摆脱任何问题。请参阅上面的更新。
  • 如果您添加了该签入,它会让 typescript 编译器知道任何通过它的代码都会有一个item,而不是undefined,这样您就可以安全地访问属性。因此,item 不会被视为 MyInterfaceType | undefined 类型,而是将其视为 MyInterfaceType(之后是 if 代码块)
【解决方案2】:

你可以这样做:

Enter Id: <input type="text" [(ngModel)]="temp.id"> 

<table class='table' *ngIf="collection">
<tbody>
   <tr *ngFor="let item of collection">
      <td>{{ item.id }}</td>
      <td>{{ item.name }}</td>
      <td><button (click)="myEvent(item)">My Button</button></td>
    </tr>
</tbody>

并在您的 myEvent

中获取所选项目
myEvent(item: any) {
  this.http.get('url', {
      params: {
          id: item.id,
          name: item.name
    }
 })
}

【讨论】:

    【解决方案3】:

    您可以使用 JavaScript 的原生方法 find() 来获取确切的对象并访问 component.ts 中的 name 字段

    let name = this.collection.find(t=> t.id == this.temp.id).name; 
    

    那么您应该能够将带有您的 Id 的名称传递给 API。

    【讨论】:

    • 谢谢。 let name = this.collection.find(t=&gt; t.id == this.temp.id) 没问题,但是当我输入名称时,它什么也不显示。
    • find方法后无法访问对象的属性!
    • 你应该可以使用 name ,只需添加一个 console.log(name) 并查看
    • 谢谢。你能告诉我,我可以将整个项目(let item = this.collection.find(t=&gt; t.id == this.temp.id))作为参数发送到我的 WEB API 吗?我应该如何传递MyInterface 类型的参数并作为等效模型进入服务器??
    猜你喜欢
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2011-06-07
    • 1970-01-01
    • 2023-01-22
    • 1970-01-01
    相关资源
    最近更新 更多