Aleksander
Aleksander

Reputation: 2813

Scroll overflowed div to vertical center on element in Angular (5)

I have a custom table consisting of divs using the flex layout rendered via angular like such:

<div class="tbody">
  <div class="tr"
       *ngFor="let ask of asks">
    <div class="td centered red">{{ask.price | number: '1.8-8'}}</div>
    <div class="td centered">{{ask.amount | number: '1.7-7'}}</div>
    <div class="td centered">{{ask.sum | number: '1.7-7'}}</div>
  </div>
  <div class="tr"> this should be in the middle</div>
  <div class="tr"
       *ngFor="let bid of bids">
    <div class="td centered green">{{bid.price | number: '1.8-8'}}</div>
    <div class="td centered">{{bid.amount | number: '1.7-7'}}</div>
    <div class="td centered">{{bid.sum | number: '1.7-7'}}</div>
  </div>
</div>

I'd like the "table" to center on the middle tr (see above excerpt) when it's rendered.

This is similar to how, for example, the Order Book looks on GDAX (see below screenshot). As you can tell from the scroll bar on the right, this is a much longer overflowed div that is currently in the middle. It is rendered in the middle to the user.

example from gdax.com

If the above is impossible, an intermediate workaround could be to center the entire div (assuming that the two datasets will be of similar length). I have also been unable to find any solution to this, so if anyone knows please feel free to submit as an answer.

Upvotes: 1

Views: 1924

Answers (1)

Jake Holzinger
Jake Holzinger

Reputation: 6063

You can use the @ViewChild decorator to get a reference to the element and set the scrollTop property.

First add some template references to the elements so they can be captured using @ViewChild.

<div class="tbody" #scrollMe>
    ...
    <div class="tr" #middle>...</div>
    ...
</div>

Then in your component implementation declare the @ViewChild element references and calculate the correct scrollTop value when the component is initialized.

export class ExampleComponent {

  @ViewChild('scrollMe') scrollElem: ElementRef;
  @ViewChild('middle') middle: ElementRef;

  ngOnInit() {
    var elem = this.scrollElem.nativeElement;
    var middleOffset = this.middle.nativeElement.offsetTop;
    elem.scrollTop = middleOffset - (elem.offsetHeight / 2);
  }

}

Upvotes: 4

Related Questions