从HTML select标签调用TS函数无法正常工作

时间:2019-08-18 07:07:34

标签: html typescript

我想从HTML select标签调用TS函数。我找到了一种方法,但是由于某种未知原因,它向我发送了错误消息。

我在select标记中使用onChange来调用该函数。在函数中,我使用以下方法在select标记中达到选项的值:

我的HTML代码:

<select id="mySelect" (change)="SelectLanguage()">
  <option value="1">English</option>
  <option value="2">Romanian</option>
  <option value="3">Hungarian</option>
</select>

我的TS代码:

SelectLanguage() {
    const e = document.getElementById('mySelect');
    const value = e.options[e.selectedIndex].value;
    console.log('e: ', value);
    this.UploadArrays(value);
}

我从此行得到以下错误消息:

const value = e.options[e.selectedIndex].value;

说:'类型'HTMLElement'上不存在“属性选项/ selecteIndex”,但是通过注销值变量,我看到它具有正确的值...因此,此行有效。其他一切工作正常,但仍然得到此错误消息...

1 个答案:

答案 0 :(得分:0)

您需要将元素强制转换为HTMLSelectElement,如下所示:

const e = document.getElementById('mySelect') as HTMLSelectElement

然后,您将拥有所需的所有属性。