更新对象角度5+时如何保持对象值的形式?

时间:2018-08-19 15:44:32

标签: html angular

我正在使用从here获得的扩展面板。我正在使用循环来创建每一行,并且我希望在面板展开时显示当前行中要编辑的数据。我对angular并不陌生,可以使用它来更新数据库。但是我所拥有的似乎不是最好的解决方案,因为当表单打开时,它会以选定的对象数据打开,但是作为占位符,则数据成为Textbox的标签,而Textbox则为空。有没有一种方法可以将当前值绑定到“文本框”值而不是占位符,并且如果我专注于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>

TypeScript函数:

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

1 个答案:

答案 0 :(得分:1)

您需要在代码中放入[(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)
      )
  }