你应该做相反的事情:你的模板应该依赖你的班级,而不是相反。
如果您有多个选项,则应该已经在组件中添加了一系列选项,并使用它填充选择。
但是既然你请求帮助来做你想做的事情,那就让我们帮忙吧:正如@ForestG建议的那样,你可以使用@ViewChild元素。
首先为您的选择添加模板参考:
...
在您的组件中
@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);
}