Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement callback function in Typescript (Angular Material)?

I am using Angular Material Dialog component, I want to pass an optional callback function, and execute if the user click the OK button. May I know how to implement it?

askUser(customData: any) {
    openDialog() {
        const dialogRef = this.dialog.open(AskDialog, {
            data: customData
        });

        dialogRef.afterClosed().subscribe(isOK=> {
            if (isOK && customData.hasOwnProperty('callback')) {
                // ??? how to execute the "customData.callback"
            }
        });
    }
}

I hope I can use the askUser() as such:

function freeGift(gift: string) { /* ... */ }
function contactPolice(phone: number, email: string) { /* ... */ }

askUser({ // callback
    displayText: 'Are you a superman?',
    callback: freeGift('blue shirt')
});

askUser({ // different callback with different arguments
    displayText: 'Are you a criminal?',
    callback: contactPolice(this.phone, '[email protected]')
});

askUser({ // no callback
    displayText: 'Do not disturb!'
});

How to PASS the callback into the customData.callback, and how to invoke and execute the function?

In other words, how to pass a function into a "variable", and execute the "variable" later with proper context?

Is it possible?

like image 450
Boo Yan Jiong Avatar asked Jul 25 '26 10:07

Boo Yan Jiong


1 Answers

You could do something like this:

askUser({ // callback
    displayText: 'Are you a superman?',
    callback: () => freeGift('blue shirt')
});

and you would call it like:

customData.callback();
like image 69
Henry Avatar answered Jul 27 '26 07:07

Henry