无法在打字稿中转换HTMLSelectElement

问题描述 投票:3回答:3

我正在使用angular 5.在.ts文件中,当我尝试将我的元素强制转换为HTMLSelectElement时,它会抛出一些错误。我检查了文档,但是值选项在HTMLSelectElement中可用。我不知道我做错了什么;

.ts文件:

里面的get_department函数:

var selected_box = <HTMLSelectElement(document.getElementById('departments')).value;

HTML文件:

<select id="departments" class="form-control" (change)="get_department();">
    <option value="">Select</option>
    <option value="prm">PRM</option>
    <option value = "crm">CRM</option>
    <option value = "crdx">CRDX</option>
  </select>

错误:

'HTMLElement'类型中不存在属性'value'。

html5 typescript angular5
3个回答
2
投票

你应该把断言放在括号内:

var selected_box = (<HTMLSelectElement>document.getElementById('departments')).value;
// OR
var selected_box = (document.getElementById('departments') as HTMLSelectElement).value;

3
投票

你这样做。

 <select class="form-control" (change)="get_department($event);">
        <option>Select</option>
        <option> PRM </option>
        <option> CRM </option>
        <option> CRDX </option>
      </select> 

在.ts

get_department(event){ var selected_box = event.target.vlue;  }

1
投票

HTML

<select id="departments" class="form-control" (change)="get_department($event)">
  <option value="">Select</option>
  <option value="prm">PRM</option>
  <option value="crm">CRM</option>
  <option value="crdx">CRDX</option>
</select>

TS

// Type assertion happens here
get_department(event: HTMLSelectElement) {
  var selected_box = event.target.value;

  console.log(selected_box);
}

您不应该直接访问该文档

document.getElementById('departments').value

  1. 它阻止使用Angular Universal部署项目
  2. 这反过来使项目的SEO优化变得不可能
  3. 此外,Angular Universal的所有其他好处都将丢失
© www.soinside.com 2019 - 2024. All rights reserved.