How to scroll to bottom after click and after data is fully loaded?

时间:2019-01-07 12:55:30

标签: angular7

I'm working on a website using Angular 7. At the bottom of the page, I have a table with animals. If a user clicks on an animal, a list of details appears underneath the table. I want the website to automatically scroll down as soon as the data is loaded and displayed on the website. On the top part of the website, I have a list of questions that narrow down the table. While the user is filling out those questions, I don't want the website to scroll down.

I tried using ngAfterContentChecked and ngAfterViewChecked, but both of them fire too often. When I fill out a question, the page jumps down.

I also added a boolean that is set to false but becomes true once new data is loaded for the details and is reset to false once the website is done scrolling. This doesn't work because both ngAfter...Checked lifecycle hooks fire before all content is actually loaded, which means the website only scrolls down part of the way.

The details are managed in their own component, and that is where I tried to manage the scrolling. The details component is displayed underneath the questions and table (which are together in one component).

Details typescript:

@ViewChild('target') target: ElementRef;
toScroll:boolean = false;

ngOnChanges(){
  this.ingredientService.showIngredient(this.creature.id)
  .subscribe(ingredients => this.ingredients = ingredients
  )
  this.toScroll = true;
}

ngAfterContentChecked(){
  if(this.toScroll){
    this.target.nativeElement.scrollIntoView();
    this.toScroll = false;
  }
}

Details html:

<h2>{{ creature.species }}</h2>
<h3>Ingredients:</h3>
<p *ngIf="ingredients?.length == 0">No ingredients</p>
<ul>
  <li *ngFor="let item of ingredients">
    {{ item.species }}
    <ul>
      <li>{{ item.function1 }}</li>
      <li>{{ item.function2 }}</li>
      <li>{{ item.function3 }}</li>
      <li>{{ item.function4 }}</li>
    </ul>
  </li>
</ul>
<div #target></div>

The desired effect is that every time the list of details changes (or every time someone clicks on an animal), the website scrolls to the bottom, but that it doesn't scroll when anything else changes.

I only got it to scroll at all changes, or not scroll down all the way to the bottom because it started scrolling before all data was loaded.

0 个答案:

没有答案