角度-属性“选项”在类型“ HTMLOptionElement”上不存在

时间:2019-02-27 06:38:25

标签: angular typescript html-select

我试图根据从其他下拉菜单中选择的值来更改下拉菜单中的选项。从网站Form Select Change Dynamic List Option Elements Tutorial中获得了它。但是,由于在Javascript上完成了教程,因此我收到错误 类型'HTMLOptionElement' 中不存在属性'options'的错误。代码如下所示:

changeWidget() {
    var roles = document.getElementById("roles") as HTMLOptionElement;
    var widgets = document.getElementById("widgets") as HTMLOptionElement;
    widgets.innerHTML = "";

    if (roles.value == "Startups") {
        var optionArray = ["|", "products|Products", "people|People", "matching|Matching"];

    }
    for (var option in optionArray) {
        var pair = optionArray[option].split("|");
        var newOption = document.createElement("option");
        newOption.value = pair[0];
        newOption.innerHTML = pair[1];
        widgets.options.add(newOption); 
    }
}

我不确定为此所需的正确类型转换是什么。是HTMLElement,HTMLSelectElement,HTMLInputElement等吗?

2 个答案:

答案 0 :(得分:1)

您应该使用HTMLSelectElement,并使用add()方法添加选项。

changeWidget() {
    var roles = document.getElementById("roles") as HTMLSelectElement;
    var widgets = document.getElementById("widgets") as HTMLSelectElement;
    widgets.innerHTML = "";

    if (roles.value == "Startups") {
        var optionArray = ["|", "products|Products", "people|People", "matching|Matching"];

    }
    for (var option in optionArray) {
        var pair = optionArray[option].split("|");
        var newOption = document.createElement("option");
        newOption.value = pair[0];
        newOption.innerHTML = pair[1];
        widgets.add(newOption); 
    }
}

答案 1 :(得分:0)

要添加选项窗口小部件,应将其设为HTMLSelectElement并将所选项目设为HTMLOptionElement

changeWidget() {
    var roles = document.getElementById("roles") as HTMLOptionElement;
    var widgets = document.getElementById("widgets") as HTMLSelectElement;
    widgets.innerHTML = "";

    if (roles.value == "Startups") {
        var optionArray = ["|", "products|Products", "people|People", "matching|Matching"];

    }
    for (var option in optionArray) {
        var pair = optionArray[option].split("|");
        var newOption = document.createElement("option");
        newOption.value = pair[0];
        newOption.innerHTML = pair[1];
        widgets.options.add(newOption); 
    }
}