How do you programatically fire a click event on a select field in an angular app?

时间:2018-12-03 12:51:27

标签: angular

I have styled a select field with a custom dropdown icon using this css on the select:

appearance: none;       /* remove default arrow */

And then using an absolutely positioned icon.

Now I want that icon when clicked to trigger the click event on the select field. I have tried using ViewChild to get the select element ref and trigger a click on it's nativeElement property but nothing happens.

@ViewChild('customInput') input: ElementRef;
click() {
  const ele = this.input.nativeElement as HTMLElement;
  ele.click();
  this.cd.detectChanges();
}

I have also tried template references:

<select #customInput>

<div class="arrow" (click)="customInput.click()"></div>

EDIT:

it is also worth noting that both approaches using .focus() instead does focus the element, but does not cause the dropdown list to appear.

3 个答案:

答案 0 :(得分:1)

克雷格(Craig),这是一个示例指南,如何以编程方式打开选择框:

let openStatus = false;

function openSelect(){
openStatus = !openStatus;
var element = document.getElementById('names');
if(openStatus){
element.size = element.length;  
 } 
 else {
 element.size = 1;   
  }
}

function handleChange(){
 alert('element slected ... closed');
 openSelect();
 }
<select id="names" onchange="handleChange()">
    <option>Foso</option>
    <option>Bar</option>
    <option>Bar</option>
    <option>Bar</option>
    <option>Bar</option>
    <option>Bar</option>
    <option>Bar</option>
    <option>Bar</option>
    <option>Bar</option>
    <option>Bar</option>
    <option>Bar</option>
    <option>Bar</option>
    <option>Bar</option>
</select>


<button onClick="openSelect()"> open Select </button>

当您单击按钮时,它会打开选​​择框。当您再次单击按钮或选择任何元素时,选择框将关闭。 我已经使用原始html和JS来解释解决方法。您也可以在角度实现相同的技术。 让我知道您是否遇到任何问题。

答案 1 :(得分:0)

Try This

Your HTML

 <select #customInput (click)="SelectClick()">
   <option value="1">Option</option>
 </select>
 <div class="arrow" (click)="click()">Click Here</div>

Component

@ViewChild('customInput') input: ElementRef;
click() {
  alert('Div click');
  const ele = this.input.nativeElement as HTMLElement;
  ele.click();
 }
 SelectClick()
 {
  alert("Select Click");
 }

答案 2 :(得分:0)

我最后到了那里。

事实证明,javaScript无法以常规方式打开选择字段,因此我重新考虑了该问题,最终使用了背景图像,该背景图像位于自定义样式的箭头所处的位置。显然,这比以前使用材质图标时要慢,所以它只是一种字体,现在它是必须渲染的图像了,但是性能影响很小,我认为这并不重要。

由于下拉图标现在仅是背景图像,因此它是选择的一部分,因此,当您单击它时,您实际上单击的是选择本身,这会使其正确打开。