I have data in the grid api, ag-grid. When I select a row and click the edit button, I would like for that row's data to be loaded into the correct form fields sot Example, But I am confused how to how properly pass my data to the mat dialog. Here is my example. First I have a service that makes a put request and another service that posts the data:
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();
})
}
Then in my table.component
class, I have the function for my button. This selects the row, calls the service, and opens the dialog.
editUser() {
const selectRows = this.gridApi.getSelectedRows();
const editSub = selectRows.map((rowToEdit) => {
return this.service.editUser(rowToEdit);
});
this.openDialog(FormComponent)
}
Here is where I am stuck, in my form class, I need to set a condition in my ngoninit
. This condition determines if I call my loadUser
function. Here, I try and use MAT_DIALOG_DATA
to load the json id which would determine if loadUsers()
should be called. But I cannot seem to access my id. I keep getting an error saying it is 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.
EDIT: Updated code. Unable to send data to the form still: TableComponent:
editUser(user) {
const dialogRef = this.dialog.open(FormComponent, {
width: '250px',
data: user
});
dialogRef.afterClosed().subscribe(result => {
this.user = user;
});
}
Form Component:
constructor( public dialogRef: MatDialogRef<FormComponent>,
private fb: FormBuilder, private service: Service, private http: HttpClient, @Inject(MAT_DIALOG_DATA) public data: Employees) {
}