Angular Typescript - 等待弹出对话框中的值

时间:2017-10-26 16:12:59

标签: html angular typescript wait

我有一个html按钮,按下时,调用一个将'display'布尔值设置为true的函数,这会弹出一个对话框,用户可以从名单列表中选择一个名称。选择名称会将“selectedName”变量设置为所选名称。

这是我的问题 - 我最初调用显示弹出对话框的相同功能需要使用所选名称进行更多处理 - 我想在单个函数调用中完成所有这些操作。像这样:

// Called by pressing an HTML button
getSelectedName() {
    display = true; // makes dialog popup appear

    // Wait for user to select a name and press a 'Confirm' button 
    // within the dialog popup

    // Once the user has selected a name, do something with it
    var person: Person;
    person.name = selectedName;
}

弹出对话框有确认/取消按钮 - 无论如何要使上述功能等待用户点击确认按钮,然后在功能中继续?

1 个答案:

答案 0 :(得分:2)

您可以创建一个在用户点击确认后解析的承诺,然后只有在承诺得到解决后才能执行您需要的任何工作。

// Called by pressing an HTML button
getSelectedName() {
    display = true; // makes dialog popup appear

    // Create a promise that resolves when button is clicked.
    const buttonPromise = new Promise((resolve) => {
        const button = document.getElementById("my-confirm-button");
        const resolver = () => {
            resolve();
            button.removeEventListener("click", resolver);
        }

        button.addEventListener("click", resolver);
    });


    // Once the user has selected a name, do something with it       
    clickPromise.then(() => {
        var person: Person;
        person.name = selectedName;
    })
}