Scroll to specific element not working correctly


#1

i’m doing this function that take the form control and loop inside it to see which element not valid
(formControlName = id ) i named all the ids with the same name of formControlName:

isSlideValid(formName) : boolean{
    if(formName.invalid){
      this.showErrorInputMessage = true;
      let target;
      let id;
      for (let i in formName.controls) {
        if (formName.controls[i].invalid) {
          target = formName.controls[i];
          id = i;
          break;
        }
      }
      if (target) {
        let yOffset = document.getElementById(id).offsetTop;
        this.content.scrollTo(0, yOffset, 4000)
      }
      return false;
    }
    return true;
  }

it works fine , but it scroll always to the top not to the specific element.
Kindly note that the form is inside a ion-slide


#2

I used this, it wokr good but look like complicated , is there another solution?

scrollTo(element:string) {
    let elem = document.getElementById(element);
    var box = elem.getBoundingClientRect();

    var body = document.body;
    var docEl = document.documentElement;

    var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
    var clientTop = docEl.clientTop || body.clientTop || 0;
    var top  = box.top +  scrollTop - clientTop;
    var cDim = this.content.getContentDimensions();

    var scrollOffset = Math.round(top) + cDim.scrollTop - cDim.contentTop;

    this.content.scrollTo(0, scrollOffset, 500);
  }

i got it from this link : https://stackoverflow.com/questions/41339158/scrollto-particular-item-of-listivew-in-ionic-2