首页 > 解决方案 > 更新对象角度5+时如何将对象值保留在表单中?

问题描述

我正在使用从这里获得的扩展面板。我正在使用一个循环来创建每一行,我希望当面板展开时它会显示当前行中要编辑的数据。我是 Angular 的新手,我有什么工作,它会更新数据库。但是我所拥有的似乎并不是最好的解决方案,因为当表单打开时,它会打开选​​定的对象数据,但作为占位符,数据会变成标签,TextboxTextbox变成空。有没有办法将当前值绑定到文本框值而不是占位符,如果我专注于Textbox它,它会保留文本供我编辑。

html:

<tr *ngFor="let search of searches">
<mat-expansion-panel (opened)="panelOpenState2 = true" (closed)="panelOpenState2 = false">
  <mat-expansion-panel-header>
    <td><span class="badge">3</span></td>
    <td>{{ search.name }}</td>
    <td><button color="warn" (click)="deleteSearch(search._id)" class="btn btn-primary float-right">Del</button></td>
  </mat-expansion-panel-header>
  <td>
    <mat-form-field>
      <input matInput placeholder="{{ search.name }}" [(ngModel)]="inputValue" name="name" type="text" class="form-control rounded-0" required>
    </mat-form-field>
  </td>
  <td><button (click)="updateSearch(search._id, inputValue)" class="btn btn-primary float-right">Edit</button></td>
</mat-expansion-panel>
</tr>

打字稿功能:

updateSearch(id, name) {
    this.searchService.updateSearch(id,name,'dd')
      .subscribe(
        res => {
          console.log(name+ 'fjjf')
          console.log(res)
          this.fetchSearches();
        },
        err => console.log(err)
      )
  }

标签: htmlangular

解决方案


你需要[(ngModel)]="search.name"输入你的代码。

试试下面的代码: -

<mat-form-field>
      <input matInput placeholder="Name" [(ngModel)]="search.name" name="name" type="text" class="form-control rounded-0" required>
</mat-form-field>

也不要忘记更新您的(click)活页夹,如下所示:-

(click)="updateSearch(search)"

您的打字稿功能可以更新如下: -

  updateSearch(search) {
    this.searchService.updateSearch(search._id, search.name, 'dd')
      .subscribe(
        res => {
          console.log(name+ 'fjjf')
          console.log(res)
          this.fetchSearches();
        },
        err => console.log(err)
      )
  }

推荐阅读