Typescript遍历所有HTML select <option>

时间:2018-04-17 10:59:20

标签: angular typescript

我正在尝试学习TypeScript和Angular。我有一个内置很多选项的html,我需要在ts文件中填充一个包含所有选项的数组。我做过类似的事情:

initializeItems() {
 var select = document.getElementById("idOfSelect");
 for (var i = 0; i <= select.length; i++ )

但是很明显,select.lenght无法工作。我该怎么办?

2 个答案:

答案 0 :(得分:0)

忘记document.getElementBy ...

Angular方式是使用@ViewChildren

这样你就可以这样写:

@ViewChildren('idOfSelect') selectedElements: QueryList<any>;

然后selectedElements.lengthselectedElements.forEach(...)将有效。

答案 1 :(得分:-2)

你应该做相反的事情:你的模板应该依赖你的班级,而不是相反。

如果您有多个选项,则应该已经在组件中添加了一系列选项,并使用它填充选择。

但是既然你请求帮助来做你想做的事情,那就让我们帮忙吧:正如@ForestG建议的那样,你可以使用@ViewChild元素。

首先为您的选择添加模板参考:

<select #mySelect>...</select>

在您的组件中

@ViewChild('mySelect') select: ElementRef;

ngOnInit() {
  const htmlOptions = this.select.nativeElement.querySelectorAll('option');
  const options = [].slice.call(htmlOptions);
  const values = options.map(opt => opt.getAttribute('value'));
  console.log(values);
}

如果你的select的id是唯一的,你也可以直接获取元素,让你跳过装饰器:

ngOnInit() {
  const select = document.querySelector('IdOfYourSelect');
  const htmlOptions = select.querySelectorAll('option');
  const options = [].slice.call(htmlOptions);
  const values = options.map(opt => opt.getAttribute('value'));
  console.log(values);
}