简体   繁体   中英

Angular4 focus on component

I have a multi-picklist component that houses a list of checkbox components. The parent component has a CSS :focus and :hover class for the mouseover. All controllable elements are in the tab index (so you can awkwardly use the keyboard to tab through the checkboxes).

Now we want to allow arrow-key navigation in the multi-picklist. Basically I need to use @ViewChild to grab the element I need and set .focus() to it. And that's exactly what I did in a different component, and that worked. However, here it does not work. The only difference is that in the component where it works my *ngFor loop iterates over a list of div s and in this case it does so over a list of components.

So what this boils down to is that I can't get the :focus pseudo class to stick to my component.The following code is not complete, just trying to get the first element focused. Sort of PoC.

MultiPicklist.component.html:

<div (keydown.ArrowDown)="arrowDownHit($event)">
  <div [hidden]="multiPicklistState === 'collapsed'" (keydown.Escape)="closeBox()" #multiPicklist>
    <app-checkbox              
      #checkboxItems
      class="multi-picklist-checkbox" 
      *ngFor="let item of picklistItemList; trackBy: trackByFunc; let i = index;"
      [fieldName]="item.value"
      [label]="item.label" 
      [chckbxId]="'multiPicklistChkbx'+title+i" 
      [tooltip]="item.tooltip" 
      [isChecked]="item.isChecked"
      (checkboxChanged)="inputChanged($event)">
    </app-checkbox>
  </div>
</div>

MultiPicklist.component.scss:

.multi-picklist-checkbox:hover, .multi-picklist-checkbox:focus{
  background-color: $multi-picklist-item-hover-bg-color;
}

MultiPicklist.component.ts:

arrowDownHit(ev){
  ev.preventDefault();
  this.multiPicklist.nativeElement.firstElementChild.focus();
}

It's worth mentioning that the :hover pseudo class works, hovering the mouse over the component gives it the correct background color. But not .focus() . Furthermore, no error is thrown,.

This is just a workaround, not an actual answer or solution.

I was able to set the focus of an HTML element inside the component. It resulted in an ugly little line of code:

this.multiPicklist.nativeElement.firstElementChild.lastElementChild.focus();

Of course in an ideal universe I'd be able to just apply the focus to the entire component, or whatever div the browser ends up seeing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM