如何使用Angular2和Typescript在表中添加和更新条目

时间:2017-09-25 08:13:25

标签: javascript html angular typescript

我有一个表格,其中有条目。我有一个编辑弹出窗口,其功能如添加和编辑。现在,如果我在弹出窗口中编辑一行的内容,它将显示我在Table中输入的内容。只有在单击“保存”后,该表必须具有上一个值,然后必须使用编辑的条目进行更新。

这是我的HTML代码:

  <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                        <md-input-container>
                            <input type="text" mdInput name="employeeDashboardID" placeholder="EmployDashboard Id" #updated [(value)]="user.employeeDashboardID" required>
                        </md-input-container>
                    </div>
                </div>
                <!-- Save and Cancel Buttons -->
                <div md-theme="reports" class="modal-footer" style="text-align: center;">
                    <div layout-align="end center" layout="row">
                        <button md-raised-button class="md-raised color-white" (click)="editUser.hide()" style="width: 45%;margin: 10px 5px;background-color: #FF5252;">Cancel</button>
                        <button md-raised-button class="md-raised color-white" (click)="editedUser(updated,user)" [disabled]="!editForm.form.valid" style="width: 45%;margin: 10px 5px;">Save</button>
                    </div>
                </div>

Ts代码:

/* edit User */
edit(user:any) {
  this.user = user;
  this.editUser.show();
}
/* Function to edit User successfully */
editedUser(updated:any,user:any) {
  console.log(user);
  console.log(updated);
  var data = {
    user_id: user.users._id,
    employee_id: user.employeeDashboardID
  }

 this.ApiService
     .changeUser(data)
     .subscribe(
       users => {
         this.toasterService.pop('success', 'updated successfully');
         this.editUser.hide();
         /* Get All Users */
           this.ApiService
               .getUsers()
               .subscribe(
                 users => {
                   this.loading = false;
                   users.sort(function(a:any, b:any) {
                         return (a._id - b._id);
                       });
                   this.users = users;
                   this.user = new User();
                 },error => {
                   console.log(error);
                 })
      },error => {
          this.toasterService.pop('error', 'Something went wrong!');
      })
}

1 个答案:

答案 0 :(得分:0)

您需要获取用户的副本,然后将该副本绑定到弹出窗口。然后在保存时,您可以更新原始用户,在取消时,只需放弃副本:

edit(user:any) {
  this.currentEditUser = JSON.parse(JSON.stringify(user)); //This is one way to make a copy, there are others such as Object.assign()
  this.editUser.show();
}

然后将弹出窗口绑定到currentEditUser并将currentEditUser传递到editedUser(updated:any,user:any)方法