简体   繁体   中英

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 eg 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 eg this doesn't answer how to deal with prefetching (resolvers). From what I know dialogs are not using route resolvers.

Thanks in advance

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' } })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM