Unable to get jQuery scrollTo() function to work within Angular 4

I have encountered an issue while using a library called ng2-pdf-viewer. The default way to stick to a page in the PDF document was not working as expected. To overcome this, I utilized jQuery's scrollTo() method to navigate to the specific .page class within the PDF. For example, scrolling to page 2 would be represented as .page:nth-child(2). While this solution works after refreshing the page, it does not auto-scroll when first landing on the page. At this point, using jQuery scrollTo seems to be the only approach that somewhat resolves the issue.

HTML

<pdf-viewer [src]="pdfSrc"
          [render-text]="true"
          [autoresize]="true"
          [original-size]="false"
          style="display: block;" (after-load-complete)="callBackFn($event)">
</pdf-viewer>

COMPONENT.TS

import { Component, OnInit, Output, EventEmitter, AfterViewInit} from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ActivatedRoute } from '@angular/router';
import { HeaderTitleService } from '@shared/service/headerTitle.service';


declare var jQuery: any;
const $ = jQuery;


@Component({
  selector: 'app-pdfview',
  templateUrl: './pdfview.component.html',
  styleUrls: ['./pdfview.component.less']
})



export class PdfviewComponent implements OnInit {


pdfSrc: string;
pdf: string;
pageNum: number = 2;
botString: string;
pageNumberVar: string;


@Output() notify: EventEmitter<String> = new EventEmitter<String>();

constructor(
   private route: ActivatedRoute,
   private headerTitleService: HeaderTitleService
) {
this.pdf = route.snapshot.params['pdfId'];
  if (this.pdf === '1') {
      this.pdfSrc = '../../../assets/pdf/emeds1.pdf';
      this.botString = 'Admission Reconciliation loaded on Page 2 - matching the word ‘reconcile’ for you.';
      this.pageNumberVar = '2';
    } else if (this.pdf === '2') {
      this.pdfSrc = '../../../assets/pdf/medrec.pdf';
      this.botService.sendMessage('I have loaded the document on page 21 showing "Medication Reconciliation"');
      setTimeout(() => {
        this.botService.sendMessage('That saved you hours of reading :)'); 
       }, 2000);
      setTimeout(() => {
        $('html, body').animate({
          scrollTop: $('.page:nth-child(29)').offset().top
         }, 300);
       }, 1000);
    }
  }


  callBackFn(pdf: PDFDocumentProxy) {
  this.botService.sendMessage(this.botString);
  }

  ngAfterViewInit() {
    setTimeout(function(){
     $('html, body').animate({
      scrollTop: $('.page:nth-child(' + this.pageNumberVar + ')').offset().top
   }, 300);
   }, 1000);
   }
}

Even after attempting to incorporate the scrollTo function within ngAfterViewInit, the auto-scroll issue still persists.

Answer №1

In my opinion, using jQuery in combination with Angular is not advisable due to its direct manipulation of the browser's DOM, which can conflict with Angular's own methods of handling the Shadow DOM.

For this particular situation, I believe you may not need the scrollTo fix anymore and should focus on getting the pdf viewer functionality to work smoothly.

When dealing with displaying the correct page, I encountered some challenges initially. However, through experimentation, I was able to configure it successfully like so:

<pdf-viewer [src]="pdfSrc"
            [(page)]="page"
            [show-all]="false"
            [rotation]="0"
            [zoom]="0.9"
>
</pdf-viewer>

It would be best to start with this setup to ensure the correct rendering of the page before gradually adding additional properties one by one to identify what functions correctly and what causes issues.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to create a JavaScript function that can be used for multiple expandable cards in HTML and CSS?

I'm dealing with a situation where I have a list of cards, and I want to be able to expand the content individually when clicking on "more info". Can someone offer advice on how to achieve this using Javascript? Check out this CodePen for reference: ...

What is the most effective method for creating posts, pages, and their corresponding URLs using Next.js and MongoDB

Here's a glimpse of my MongoDB data: { "_id": { "$oid": "630f3c32c1a580642a9ff4a0" }, "title": "this is a title", "paragraph": "this is a paragraph" } Now, let's t ...

Pass a JavaScript array variable to a PHP script utilizing jQuery Ajax and receive a string output instead of an array

Whenever I attempt to transmit a JavaScript array to a PHP script via Ajax, the output of $_POST['file_paths'] when var_dumped shows up as a string instead of an array. My goal is to have the output in array format rather than in string format. C ...

Troubleshooting issue: EJS loop not functioning correctly when handling JSON information

Having an issue with looping in an EJS file. Here's the data I'm working with: { "name": "Marina Silva", "info": [{ "periodBegins": "Sun Apr 14 23:48:36 +0000 2011", "periodFinishes": "Sun Apr 7 23:48:36 +0000 201 ...

Is there a way to retrieve the ngModel reference of a child element within a directive's

I am currently utilizing bootstrap-colorpicker along with an angular directive in my project. Within my form, there is a colorpicker that I want to monitor for any changes. However, since the colorpicker jQuery plugin updates the value of the colorpicker, ...

Assigns functions outside of the Angular class to specific keys

import {Injectable, OnDestroy} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {Observable} from 'rxjs/Observable'; import { catchError, tap } from 'rxjs/operators'; import {environment} ...

Customize URL paths with separate templates using ui-router

I'm currently utilizing angular-ui-router's nested states feature to manage my views. My objective is to set up two routes: /artists - this will display the main page for all artists /artists/:id - this route will showcase the individual artist ...

Unable to forward to another page using NodeJS (Express)

After spending a considerable amount of time trying to find a solution, I finally managed to create a simple button click redirection using NodeJS and Express. However, when clicking on the "Next page" button in my index.html file, I encountered an error s ...

Capturing the dynamic server response with nested JSON structures

I am in the process of creating a dynamic data-binding function named assemble that requires two input parameters: server response (JSON) - nested JSON object. instruction set (JSON) - a configuration object that dictates the binding. The Issue: The cur ...

Begin using datatables with the xp:table component

Within an XPage, there is a table component: <xp:table id="tblProposals"> I am looking to apply the datatables plugin to this table using a scriptblock component: <xp:scriptBlock id="scriptInitProposals"> < ...

Utilize jQuery to broadcast messages containing textarea content to all users from the database via email

Currently, I am facing an issue while trying to send an email to all users from the database using the value from a textarea. It seems like there is an error in my approach. Upon further inspection, I suspect that the problem lies in selecting the data fro ...

Is there a way to delete a wrapper (parent element) in Angular without deleting the child element as well?

The solution provided in this answer on Stack Overflow addresses jQuery and not Angular or TypeScript. My inquiry bears resemblance to this question raised on a forum, but I am specifically looking for a resolution within the context of Angular. Is there ...

Tips on implementing conditional validators in Angular's formBuilder

Is it possible in Angular 7.x to use formBuilder and ReactiveForms to apply a validator to a form based on the user's role? For instance, if the user has a specific role, they would be required to input certain fields. The user information is stored i ...

How can the action value be passed in effects for switchMap using both another switchMap and filter?

There is a certain code snippet @Effect() myEffect$ = this.actions$.pipe( ofType(MyActions.doSomething), tap(() => this.store.dispatch(MyActions.doSomething2())), switchMap(action => { that is functioning as expected. In order to inj ...

Challenges encountered during the setup of Ngx-Admin

Hello, I am new to Angular and I am trying to install the ngx-admin template. However, I encountered the following errors. Can someone please provide guidance on how to resolve these issues? npm WARN deprecated <a href="/cdn-cgi/l/email-protection" c ...

angular table disabled based on condition

I have a table in my HTML file and I am trying to figure out how to disable the onClick function if the start date is greater than the current date. <ng-container matColumnDef="d"> <th mat-header-cell ...

Does getServerSideProps execute for each page request, or solely for HTTP requests?

Does getServerSideProps execute with every page request, or is it specifically for HTTP requests? ...

Tips for Omitting Hours, Minutes, and Seconds from AngularJS Date Display

Currently, I am retrieving data from a JSON file using the $http.get request. The format in which the date is received in my JSON file is as follows: "date": "2016-10-24 15:14:53" I would like to convert this date format to display as: October 10 2016 (e ...

Personalized labels for your JQuery Mobile sliders

Struggling to make this work correctly, I aim to introduce tick marks and custom labels into jQuery Mobile's slider widget. My goal is to add tick markers at 0, 25, 50, 75, and 100 with a unique string above each tick. Additionally, I want these label ...

send the variable to the deferred done function

Having trouble passing a variable into a done callback. var getDataForCompany = function(company_id) { $.ajax({ type: "post", url: url, data:{ company_id: company_id } }).done(function(returnedData, textStatus, j ...