Service causing issues with Angular HTMLElement functionality, operates normally otherwise

I've been encountering some issues with my code specifically when it's called from the service.

In the app.component.html file, I have:

<div id="wrapper"></div>

Executing this code:

this.targetElement = document.getElementById('wrapper') as HTMLElement;

In app.component.ts, it works perfectly fine. However, I'm attempting to migrate it to a service, so I implemented the following:

import { Injectable } from '@angular/core';
import * as mylib from '../../assets/index.js';

@Injectable({
  providedIn: 'root'
})
export class ViewerService {

  window: any = window;
  targetElement: HTMLElement;
  viewer: any;

  constructor() { }

  viewerInit() {
    this.targetElement = document.getElementById('wrapper') as HTMLElement;
    return this.targetElement;
  }

}

Subsequently, when I invoke the service from app.component.ts...

ngOnInit() {
  this.viewerService.viewerInit();
}

The code doesn't seem to work from the service endpoint...

How can I rectify this situation?

Answer №1

ngOnInit function should be replaced with the AfterViewInit hook for better implementation.

public ngAfterViewInit(): void {
  this.viewerService.viewerInit();
}

If you'd like to pass the element into the service, consider the following approach:

class AppComponent implements AfterViewInit {
  @ViewChild('wrapper') wrapper: TemplateRef<any>;

  public ngAfterViewInit(): void {
    this.viewerService.viewerInit(this.wrapper.elementRef.nativeElement);
  }
}

Here is how the template should look:

<div #wrapper></div>

And the ViewerService should be structured as follows:

export class ViewerService {

  window: any = window;
  targetElement: HTMLElement;
  viewer: any;

  constructor() { }

  viewerInit(target?: HTMLElement) {
    if (target) {
      this.targetElement = target;
    }
    return this.targetElement;
  }
}

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

One typical approach in React/JavaScript for monitoring the runtime of every function within a program

Experimenting with different techniques such as performance.now() or new Date().getTime() has been done in order to monitor the processing time of every function/method. However, specifying these methods within each function for time calculation purposes h ...

Offset the CDK Menu

Is it possible to adjust the position of the trigger using the CDK overlay by setting an offset (e.g. cdkConnectedOverlayOffsetY)? I've looked through the CDK menu documentation but couldn't find a similar functionality. Is there a method to achi ...

Encountering an issue when attempting to integrate material-ui into the jhipster project

After creating a jhipster application which utilizes Angular as the front end UI framework, I am encountering issues with the versions of jhipster and node as specified below: jhipster: 7.9.3, npm: '9.6.5', node: '18.16.0', My objectiv ...

Angular is flagging the term 'Component' as defined but not utilized within the codebase

Our Angular framework was recently upgraded to version 14 along with all dependent packages to their latest versions. However, post-update, an eslint error is popping up stating that the 'Component' import is defined but never used (unused-import ...

The Append method in FormData is not functioning properly within Angular

I'm facing a challenge in my Angular application where I need to enable image uploads to the server. The issue arises when attempting to add a selected file to the newly created FormData object. Below is the relevant TypeScript component snippet: ima ...

The process of releasing a component created with angular-starter onto npm is now underway

After creating angular components with the Angular Starter Kit from https://github.com/AngularClass/angular-starter, I am looking to package them and deploy them on NPM for easy use in other projects. However, I found the documentation to be lacking in thi ...

Convert HTML Form to PDF or Docx with Angular 4

My current setup involves Angular 4 with Node and MySQL. I have a form that, upon submission, needs to trigger a Save As... dialog box for the user to save the entered form contents as either a PDF or Word Doc. I've attempted using htmlDox and saveAs ...

What is the best way to verify observables during the ngOnInit phase of the component lifecycle?

Despite reading numerous articles on testing observables, such as learning how to write marble tests, I am still struggling to find a clear solution for testing a simple observable in the ngOnInit lifecycle of my component. ngOnInit(): void { this.sele ...

Preserve final variable state - Angular

My function looks like this: flag: boolean = false; some_function(){ var foo = some_num_value; var bar = foo; // Storing value in a separate variable if(this.flag){ v ...

Challenge: Visual Studio 2015 MVC6 and Angular 2 compilation issue - Promise name not found

Initially, I've made sure to review the following sources: Issue 7052 in Angular's GitHub Issue 4902 in Angular's GitHub Typescript: Cannot find 'Promise' using ECMAScript 6 How to utilize ES6 Promises with Typescript? Visual ...

Prevent TypeScript from generalizing string literals as types

I have a constant Object called STUDY_TAGS with specific properties const STUDY_TAGS ={ InstanceAvailability: { tag: "00080056", type: "optional", vr: "string" }, ModalitiesinStudy: { tag: "00080061", type: " ...

Exploring Next.js 13: Enhancing Security with HTTP Cookie Authentication

I'm currently working on a web app using Next.js version 13.4.7. I am setting up authentication with JWT tokens from the backend (Laravel) and attempting to store them in http-only cookies. Within a file named cookie.ts, which contains helper functio ...

Iterating through an object using the forEach method (uncommon practice)

Greetings, I have the following object: data = { name: undefined, age: undefined, gender: undefined }; I am looking to iterate through each key and value pair in this object and perform an action. Here is my attempt: this.data.forEach((item: ...

Properly cancel subscriptions using post, put, patch, or delete requests in Angular

I'm curious about the most effective method for unsubscribing a post, put, patch, or delete on the HTTP service. For instance, take this method that is called in a page to save an object: public add(obj) { const sub = this.service.post('/path/t ...

Tips for incorporating moment.js library into an Angular 2 TypeScript application

I attempted to utilize TypeScript bindings in my project: npm install moment --save typings install moment --ambient -- save test.ts file content: import {moment} from 'moment/moment'; I also tried without using TypeScript bindings: npm inst ...

Is there a way for me to properly type the OAuthClient coming from googleapis?

Currently, I am developing a nodemailer app using Gmail OAuth2 in TypeScript. With the configuration options set to "noImplicitAny": true and "noImplicitReturns": true, I have to explicitly define return types. Here is a snippet of my code: import { goog ...

The Main Page is always the default destination when navigating with Angular Router

Having an issue with Angular Router (Angular 11). Here is my routing configuration: {path: '', redirectTo: '/login', pathMatch: 'full'} {path: 'login', component: LoginComponent} {path: 'verdicts', componen ...

Protractor end-to-end tests: extracting chosen menu item from page model function

My website has a navigation menu with different items. I'm using a page model for end-to-end tests. In one of my test specs, I need to call a function from the page model that does the following: Check that only one item in the menu has a specific ...

Encountering a 404 error when trying to deploy an Angular application

After following the Angular documentation for deployment, I am deploying my angular application on github pages. The steps I have taken include: 1. Running "ng build --prod --output-path docs --base-href /<project_name>/". 2. Making a copy of docs/ ...

What is preventing me from generating Face3 in my ThreeJS Typescript project

Currently, I'm in the process of generating a Mesh using Face3 within a TypeScript project that utilizes Three.js. However, I've encountered a few issues along the way. const points = [ new Face3(-1, 1, -1),//c new Face3(-1, -1, 1),//b ...