Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to setTimeout in Angular 2+

I am dispatching the data to ngrx store. After that I want to scroll to a specific div, which is using this data from store.

@ViewChild('datalist') private myScrollContainer: ElementRef; 

this.store.dispatch(new SetClientSearchResultsAction(filteredData));

setTimeout(() => {
this.myScrollContainer.nativeElement.scrollIntoView({ behavior:'smooth', block: 'start'});
 }, 300);

Below is the HTML div.

<div  #datalist id="mydata" *ngIf="clientSearchResults$ | async  as searchResults" 
class = 'result'>
  <p> hellooo</p>
</div>

I am getting the scroll at my div after dispatching the data to store. But I do not want to use setTimeout. It is unnecessarily waiting for 300 milliseconds. Is there any alternative way to do that ? I just want to scroll to my div, when my data is dispatched or ngif condition got fulfilled.

Below is the constructor of my component where I am getting the value from Store.

constructor(private store: Store<AppState>,
    private formBuilder: FormBuilder, private _clientService: ClientService) {
    this.clientSearchResults$ = this.store.select('searchResults');
  }
like image 591
Nimish goel Avatar asked Apr 03 '18 09:04

Nimish goel


Video Answer


1 Answers

You can use Lifecycle hook, AfterViewInit Respond after Angular initializes the component's views and child views / the view that a directive is in.

class MyComponent implements AfterViewInit {
  ngAfterViewInit() {
    // ...
  }
}
like image 127
Rahul Sharma Avatar answered Nov 09 '22 05:11

Rahul Sharma