Angular / aggrid:如何将行数据传递到表单?(材料对话框)

时间:2018-08-21 16:15:46

标签: angular angular-material httpclient ag-grid

我在网格API ag-grid中有数据。当我选择一行并单击“编辑”按钮时,我希望将该行的数据加载到正确的Example表单字段中,但是我很困惑如何正确地将数据传递到Mat对话框。这是我的例子。首先,我有一个发出放置请求的服务和另一个发布数据的服务:

editUser(employee: Employees) {
  return this.http.put(this._url + '/' + employee.id, httpOptions).pipe(
    map((res: Response) => res.json)
  )
}

saveUser(employee: Employees) {
  return this.http.post(this._url, employee, httpOptions).subscribe((res: any) => {
    res = employee
    this.componentMethodCallSource.next();
  })
}

然后在我的table.component类中,我具有按钮的功能。选择行,调用服务,然后打开对话框。

editUser() {
  const selectRows = this.gridApi.getSelectedRows();

  const editSub = selectRows.map((rowToEdit) => {
    return this.service.editUser(rowToEdit);
  });
  this.openDialog(FormComponent)
}

在这里,我被困在表单类中,我需要在ngoninit中设置一个条件。此条件确定我是否调用我的loadUser函数。在这里,我尝试使用MAT_DIALOG_DATA来加载json ID,该ID将确定是否应调用loadUsers()。但是我似乎无法访问我的ID。我不断收到错误消息,说它是undefined

表单组件

employeeInfo: Employees;
userId: number;

constructor(
  public dialogRef: MatDialogRef<FormComponent>,
  private fb: FormBuilder, 
  private service: Service, 
  private http: HttpClient, 
  @Inject(MAT_DIALOG_DATA) public data: any
) {
  this.userId = this.data.userId;
}

ngOnInit() {
  this.createUserForm();
  if (this.userId > 0) {
    this.loadUser();
  }
}

createUserForm() {
  this.frmUser = this.fb.group({
    id: [],
    firstName: ["", [Validators.required]],
    lastName: ["", Validators.required],
  })
}

onSave() {
  this.employeeInfo = this.frmUser.getRawValue();
  this.employeeInfo.id = this.userId;
  this.service.saveUser(this.employeeInfo)
  this.dialogRef.close({
    success: 'success',
    data: {
      emp: this.employeeInfo.id
    }
  })
}

loadUser() {
  this.service.getData(this._url).subscribe((res: any) => {
    this.frmUser.patchValue({
      firstName: res.FirstName,
    })
  })
}

我正在为表单使用MatDialogRef。

编辑:更新了代码。无法将数据仍然发送到表单: TableComponent:

editUser(user) {
  const dialogRef = this.dialog.open(FormComponent, {

    width: '250px',
    data: user
  });

  dialogRef.afterClosed().subscribe(result => {
    this.user = user;
  });
}

表单组件:

  constructor( public dialogRef: MatDialogRef<FormComponent>,
    private fb: FormBuilder, private service: Service, private http: HttpClient,  @Inject(MAT_DIALOG_DATA) public data: Employees) { 
    }

1 个答案:

答案 0 :(得分:1)

我建议您阅读Material Dialog的文档。如果要在对话框上显示用户编辑表单,我也不确定为什么要使用formBuilder创建表单。

您将数据传递到open实例的MatDialog方法。

constructor(public dialog: MatDialog) {}

this.dialog.open(DialogOverviewExampleDialog, {
  width: '250px',
  data: user
});

user是包含要传递给模态的数据的变量。

我已经创建了一个StackBlitz Project复制您的案件。让我知道这是否是您想要的。

我已经从JSONPlaceholder API中获取了数据,我只是在反映用户对Material Table而不是您的AgGrid Table所做的更改。

但是您的主要问题是在表单组件中获取userId。这就是已经在项目中复制的东西。那应该可以帮助您了解问题的根源所在。

注意:请确保使用以下版本以避免任何版本不匹配错误:

@角度/材质-6.4.6 @ angular / animations-6.0.5

请查看“项目的依赖关系”部分,以获取有关所安装软件包版本的更多信息。