7

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?

2 Answers 2

11

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();
Sign up to request clarification or add additional context in comments.

Comments

0

This can be achieved fairly easily, you can execute a function by just using (). Made an example app to elaborate; https://stackblitz.com/edit/angular-8drwks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.