Tuesday, 23 April 2019

Angular: pass functions to service inside an object

I have a component where i pass what i want to display inside a modal like this :

  openConfirmModal() {
    this.modalService.openConfirmModal(
      {
        message: 'sure?',
        buttons: [
          {
            name: 'Close',
          },
        ]
      }
    );
  }

The modal service is like this :

  openConfirmModal(data: Object) {
    const dialogRef = this.dialog.open(ConfirmComponent, {
      width: '300px',
      data: new ModalConfirmData({
        message: Object.values(data)[0],
        actions: Object.values(data)[1]
      })
    });
  }

Inside my ConfirmComponent i have :

export class ConfirmComponent {

  constructor(
    @Inject(MAT_DIALOG_DATA)
    public data: ModalConfirmData
  ) { }

}

export class ModalConfirmData {
  title: string;
  actions: Array<Object>;

  constructor(data?) {
    if (data) {
      this.title = data.message;
      this.actions = data.actions;
    }
  }
}

The html code of the ConfirmComponent is like this :

<h2 mat-dialog-title></h2>
<mat-dialog-actions *ngFor="let act of data.actions">
  <button mat-raised-button color="primary">
    
  </button>
</mat-dialog-actions>

Now everything works fine with this, but what i want to do right now is to pass a function to my service in order for it to consume it. Till now all i do is pass the name of the buttons but now i want to pass the name of the button as well as its behavior.

I want to pass something like this but i don't know how :

{
  name: "Close",
  callback: async (modalComponent) => {
    modalComponent.close();
  }
}

so that i can do in my html something like this :

<mat-dialog-actions *ngFor="let act of data.actions">
  <button mat-raised-button color="primary" (click)="act.callback">
    
  </button>
</mat-dialog-actions>

Can anyone please tell me how to pass functions inside an object to a service



from Angular: pass functions to service inside an object

No comments:

Post a Comment