3

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

Florence
  • 1,641
  • 3
  • 13
  • 23

1 Answers1

1

try this,this should work.

@ViewChild('suggestion') suggestion: ElementRef;

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

ngAfterViewInit(){
    this.renderer.invokeElementMethod(this.el.nativeElement, 'focus', []);
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
micronyks
  • 54,797
  • 15
  • 112
  • 146
  • 2
    What is `@ViewChild()` for in your answer? You should keep the `this.renderer.invokeElementMethod(...)` it's more angulary – Günter Zöchbauer Aug 01 '16 at 08:59
  • 1
    @crystal_test : try this if it doesn't work for you : https://stackoverflow.com/questions/38944725/how-to-get-dom-element-in-angular-2 – micronyks Oct 22 '17 at 07:54