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();
}
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:
Using this way, our modal will be free of business logic. Especially important for generic modals, like confirmation, user inputs, ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With