Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice in angular, material to reuse component in dialog?

In my business application I have the requirement to select records in a list, update the record data, select next item in list, and so on.

Use Case 1 Select item in list, open a dialog, manipulate data there and then return to list

Use Case 2 Navigate to page (via router), manipulate data there, navigate further from there

So what I want to avoid is to implement my business component twice. First time to make it work with the dialog and second time to make it behave like a "normal" component e.g. with prefetching data by resolver etc.

Anybody can tell me what is the best practice to do this in angular? Use component with router and open it in a dialog as well

I've found this one here==> Dynamically load a component inside a Material MatDialog

But e.g. this doesn't answer how to deal with prefetching (resolvers). From what I know dialogs are not using route resolvers.

Thanks in advance

like image 760
Karl Avatar asked Feb 14 '19 09:02

Karl


People also ask

How do you create a reusable mat dialog component in angular 8?

Creating the module<mat-dialog-content> : Primary scrollable content of the dialog. <mat-dialog-actions> : Container for action buttons at the bottom of the dialog. mat-dialog-close : Added to a <button> , makes the button close the dialog with an optional result from the bound value.

How do you use MatDialogRef?

The MatDialogRef provides a handle on the opened dialog. It can be used to close the dialog and to receive notifications when the dialog has been closed. Any notification Observables will complete when the dialog closes. dialogRef.


1 Answers

If you are using Angular Material you can reuse your business component by adding the @Optional() decorator to @Inject(MAT_DIALOG_DATA). So your reusable component looks somewhat like:

export class MyBusinessComponent implements OnInit {
  data: any;
  constructor(
   @Optional() @Inject(MAT_DIALOG_DATA) private dialogData: any,
   private route: ActivatedRoute
  ) {
    this.data = dialogData ? dialogData : null;
  }

  ngOnInit() {
    if (dialogData) {
      this.data = dialogData
    } else {
      this.data = this._route.snapshot.data
    }
  }
}

When you want to use the component as a dialog you put:

const dialogRef = this.dialog.open(PriceBreakupSectionComponent, { data: { somedata: 'somevalue' } })
like image 140
Saptarshi Bose Avatar answered Sep 28 '22 07:09

Saptarshi Bose