Reputation: 213
Is it possible to pre-populate and 'Edit' form in Angular Material openDialog ? The form is a reactive one.Main component has the url with id of the user, when the button is clicked, openDialog suppose to pop up with populated form based on the 'Id' passed from the main component.However I tried to do this but says Undefined in console log and fields are empty and not populated. Any help will be beneficial.
Upvotes: 0
Views: 332
Reputation: 2108
Short version of dialogs that I hope helps:
Open one with relevant options plus your own data (in this case seems to be at least an ID).
this._dialog.open(MyEditDialogComponent, {
maxHeight: '90%',
maxWidth: '90%',
...etc,
data: {id: 123}
});
I've slapped it in an object but if you only care about an ID, not really a requirement (I have gained the habit of making most things an object these days(.
Next up is to use it in your dialog:
export class MyEditDialogComponent implements OnInit {
constructor(@Inject(MAT_DIALOG_DATA) public data: {id: number}) { }
public ngOnInit(): void {
// use it...
const id = this.data.id;
}
}
Given you're only sending an ID, I assume you have some backing service so that the dialog can go fetch its own data to fill the edit fields.
Another option is to use the dialog as a pure ui-side editor only. Assuming your main page (component) is already displaying all of those fields and already has all of that data, then you could just pass all of that to the dialog, and the dialog could pass back the modified data.
The parent component could then handle the back-end comms.
If you want to deal with outputs from dialogs, start by outputting data when you close them (e.g. via a save button):
export class MyEditDialogComponent implements OnInit {
constructor(@Inject(MAT_DIALOG_DATA) public data: {id: number}
private readonly dialogRef: MatDialogRef<MyEditDialogComponent>) {
}
public onCloseClicked(): void {
this.dialogRef.close({some: 'data'});
}
}
And then the parent can use it:
const sub = this._dialog.open(MyEditDialogComponent, {
maxHeight: '90%',
maxWidth: '90%',
...etc,
data: {id: 123}
})
.subscribe((result: {some: string}) => {
sub.unsubscribe();
// do something with your output
const outputData = result.some;
});
Upvotes: 0