Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular material dialog pass dynamic function when clicked on save

dialog.ts

export class DialogComponent {
    constructor(private service: RestService, private dialogRef: MatDialogRef<DialogComponent>) {
    }

    no() {
        this.dialogRef.close();
    }

    save() {
        const url = 'https://gorest.co.in/public-api/users'; 
        const options = {headers: HttpHeaders, params: HttpParams};

        const getResp: any = this.service.Get(url, options);       
        this.dialogRef.close();

    ///THIS save() FUNCTION HARDCODED, BUT I WANT TO MAKE RESTCALL DYNAMICALLY WHEN ANYONE CLICKS SAVE BUTTON IN DIALOG
    }

}

dialog.html

<mat-dialog-actions>

    <button class="mat-raised-button"
            (click)="no()">
        no
    </button>

    <button class="mat-raised-button mat-primary"
            (click)="save()">
        save
    </button>

</mat-dialog-actions>

component1.ts

 getUsers() {

    const dialogConfig = new MatDialogConfig();

    const dialogRef = this.dialog.open(DialogComponent,
        dialogConfig, passSomeRestCall-1-FunctionSomehow());  
  }

component2.ts

 getEmployees() {

    const dialogConfig = new MatDialogConfig();

    const dialogRef = this.dialog.open(DialogComponent,
        dialogConfig, passSomeRestCall-2-FunctionSomehow());  
  }

Above 2 components have to make use of Dialog Component dynamically, currently above save() hardcoded with some restcall, but actually rest call needed when clicked on save() for both above components. So, in short, save() button should happen dynamic restcall based on the component.

Could anyone please help me on above, I am very new to angular.

EDIT:

 for (let i = 0; i < this.items.length; i++) {
      this.service.makeRestCall(this.items[i]);
    }

How do I pass above for loop logic in dialog component? I should be able to do some business logic dynamically inside save() based on component like below

save(){
   dynamicMethod() // this should be passed somehow from a component
  this.dialogRef.close();
} 
like image 389
john Avatar asked Oct 17 '25 19:10

john


1 Answers

You do not need to pass the callback method. It should be part of modal's parent. Only you have need is to set @Output into the modal with type EventEmitter. Like:

@Output() save = new EventEmitter<boolean>();

On Save button just implement:

handleSave: void {
  this.save.emit(true);
}

Parent will listen this @Output and handle it properly.

dialogRef.componentInstance.save$.subscribe((res) => {
    // Here is your business logic 
  }
);

So:

  1. If after processing is everything OK, you can use dialogRef in your parent and close the modal (dialogRef.close()).
  2. If something is wrong, modal will not be closed.

Using this way, our modal will be free of business logic. Especially important for generic modals, like confirmation, user inputs, ...

like image 147
user3007799 Avatar answered Oct 20 '25 08:10

user3007799