Florence
Florence

Reputation: 1721

How to set focus on a div

I have several div in a page

<div >...
<div >....
<div  class="input-field col s12" style="display : inline-block;">
  <span style="width: auto;cursor: pointer;position: absolue">
  <input  type="text" [(ngModel)]="query"
           (keyup)="handleKeyPress($event)"
            style="padding: 4px;" (click)="displayDropdown();" >

  <div  #suggestion class="suggestions" *ngIf="filteredList.size > 0"  tabindex="-1">
  <ul class="ulsuggestions" >
     <li *ngFor="let item of filteredList| maptoiterable" style="cursor: default;">
        <bold> {{item.key}}</bold>
        <ul style="list-style-type: none;">
           <li *ngFor="let val of item.value" >
             <a (click)="select(val)"  style="cursor: pointer;" (keyup)="handleKeyPress($event)" tabindex=-1  #item>{{val}}</a>
            </li>
        </ul>
    </li>
  </ul>
</div>

In this div #suggestion , there is a scrollbar and also in main page In my code , I want to give focus to this div to allow when keypress arrow, down the div scrollbar but not the scrollbar of main page .

i had tried

 @ViewChild("suggestion")
 suggestion: ElementRef;
  this._renderer.invokeElementMethod(this.suggestion.nativeElement, 'focus', []);

but when the div scrollbar is at the top of the div , it is the scrollbar of main page that goes back

Upvotes: 3

Views: 6170

Answers (1)

micronyks
micronyks

Reputation: 55443

try this,this should work.

@ViewChild('suggestion') suggestion: ElementRef;

constructor(private renderer:Renderer, private el: ElementRef){
}

ngAfterViewInit(){
    this.renderer.invokeElementMethod(this.el.nativeElement, 'focus', []);
}

Upvotes: 1

Related Questions