我有网格api,ag-grid中的数据 . 当我选择一行并单击编辑按钮时,我希望将该行的数据加载到正确的表单字段sot Example中,但我很困惑如何将我的数据正确传递到mat对话框 . 这是我的例子 . 首先,我有一个服务,它发出一个put请求和另一个发布数据的服务:
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)
}
这是我被困的地方,在我的表单类中,我需要在我的_1279338中设置一个条件 . 此条件确定我是否调用_129339_函数 . 在这里,我尝试使用 MAT_DIALOG_DATA
来加载json id,这将决定是否应该调用 loadUsers()
. 但我似乎无法访问我的身份 . 我一直收到一个错误,说它是 undefined
.
Form Component
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,
})
})
}
I am using the MatDialogRef for my form.
编辑:更新的代码 . 无法将数据仍发送到表单: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 回答
我建议你阅读Material Dialog的文档 . 如果要在对话框中显示用户编辑表单,请使用formBuilder创建表单 .
您将数据传递给
MatDialog
实例的open
方法 .user
是包含您将传递给模态的数据的变量 .我创建了一个StackBlitz Project复制你的案子 . 如果这是您正在寻找的,请告诉我 .
我从JSONPlaceholder API获取了数据,我只是简单地将用户所做的更改反映到Material Table而不是AgGrid Table中 .
但是你的主要问题是在表单组件中获取userId . 所以这是在项目中复制的东西 . 这应该可以帮助您了解问题的真相 .
NOTE :确保使用以下版本以避免任何版本不匹配错误:
@ angular / material - 6.4.6 @ angular / animations - 6.0.5
有关已安装软件包版本的更多信息,请查看项目的“依赖项”部分 .