Angular component unable to locate specified DOM element during lazy loading

I am currently working with a nebular stepper component and I have implemented lazy loading for the final step. Within this component, there is a need to target an element by its id and make some modifications to it.

Below is the structure of the stepper component where lazy loading is applied:

Html-

 <nb-step [label]="labelFour">
          <ng-template #labelFour>Fourth step</ng-template>
          <h3>Edit Your Image</h3>
          
          <div class="container step-container">
              <ng-template #canvasContainer ></ng-template>
              
            
          </div>


          <button nbButton nbStepperPrevious>prev</button>
          <button nbButton nbStepperNext>next</button>
</nb-step>

TS-

  @ViewChild('canvasContainer', {read: ViewContainerRef}) canvasContainer: ViewContainerRef;
  canvasInitialized = false;

  async createCanvas() {
    await this.lazyLoadCanvas();
    this.canvasInitialized = true;
    
  }
  private async lazyLoadCanvas() {
    const {CanvasComponent} = await import('../../single/canvas/canvas.component');

    const canvasFactory = this.cfr.resolveComponentFactory(CanvasComponent);
    const {instance} = this.canvasContainer.createComponent(canvasFactory, null, this.injector);
    

  }
  noDesignSelected:boolean;
  thirdStepNext(){           //Third step is clicked
   
    if(this.postDesignService.designID != -1){
      this.stepper.next();
      this.noDesignSelected = false;
      this.createCanvas();
    } else {
      this.noDesignSelected = true;
    }
    
  }

Here is the component that gets loaded in:

Html-

<div class="canvas-bg">
    <div id="container" ></div>
</div>

TS-

ngAfterViewChecked() {
    document.getElementById('container').classList.add('test');   //error here

    this.stage = new Konva.Stage({
      container: 'container',            //error here
      width: this.stageWidth,
      height: this.stageHeight,
    });
}

The error message indicates that the element with id 'container' cannot be located.

I have tried using ngOninit, ngAfterViewInit, and ngAfterViewChecked (as shown above). Additionally, I attempted assigning the element to a ViewChild and modifying the style of that viewchild without success.

Answer №1

Consider utilizing a ViewChild with the identifier as #ref instead of an id

For instance:

<div class="canvas-bg">
    <div *#ref* id="container" ></div>
</div>

In your typescript file:

@ViewChild("ref") ref;

Then, within ngAfterViewInit invoke it like

this.ref.nativeElement.textContent

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

angular2 - Having trouble retrieving data from subject

Why am I unable to successfully initialize and retrieve data from a service using a subject in Angular? HomeComponentComponent.TS export class HomeComponentComponent implements OnInit { public homeSub; constructor( private subService: SubjectServ ...

The concept of 'this' in TypeScript classes compared to JavaScript's scope

Is there a way to change the custom icon of a video when it is toggled between Play and Pause? ngAfterViewInit() { const vdoCont = document.querySelector('.video-player'); const vdo = vdoCont.querySelector('video'); vdo.addEventL ...

Creating a Button within the Dialog Component Header in PRIMENG for Angular 4

I need help adding buttons to the dialog window header in primeng. You can find the code at https://www.primefaces.org/primeng/#/dialog. The task is to insert two buttons (with icons like a calculator and question mark) on the right side of the top header ...

The binding element 'dispatch' is assumed to have the 'any' type by default. Variable dispatch is now of type any

I came across this guide on implementing redux, but I decided to use TypeScript for my project. Check out the example here I encountered an issue in the AddTodo.tsx file. import * as React from 'react' import { connect } from 'react-redux ...

When attempting to incorporate a third-party library into Angular2 using the CLI, the process did not go as smoothly as anticipated

Trying to integrate a third party JavaScript library sockJS into my Angular2 project... system.config.ts: /** Mapping relative paths to URLs. */ const map: any = { 'sockjs-client': 'vendor/sockjs-client/' }; /** Configuration for use ...

Using global variables in local Angular-cli components by importing them

Here is an example of my folder structure in Angular CLI: MyApp/ src style/ page/ normalize.less styles.less In my angular-cli.json file, I have the following configuration: "app":{ "styles": [ "./style ...

Tips for importing font files from the node_module directory (specifically otf files)

We cannot seem to retrieve the fonts file from the node module and are encountering this error message. Can't find 'assets/fonts/roman.woff2' in 'C:\Projects\GIT2\newbusinessapp\projects\newbusinessapp\src ...

Tips for troubleshooting an Angular Service that is not properly injecting itself into the application

I offer a simple service: import { Injectable } from '@angular/core'; import { MdSnackBar, MdSnackBarConfig } from '@angular/material'; @Injectable() export class AlertsService { alerts: string[]; constructor(private snackBar: Md ...

The keys from one parameter are found within the keys of another parameter

I need help with a function that is defined like this: const func = (array: {}[], object: {}) => {} The keys of objects within the array should match the keys in the object. Is there a way to accomplish this? ...

Using Typescript to inherit from several classes with constructors

I am trying to have my class extend multiple classes, but I haven't been able to find a clean solution. The examples I came across using TypeScript mixins did not include constructors. Here is what I am looking for: class Realm { private _realms: C ...

What is the process for subscribing to or obtaining Err from the service?

Here is the sequence of events in my application: page/component --> service --> a remote API The page calls the service this.service.addData(...); The service uses the HttpClient which returns an Observable, so addData(...) { ... return th ...

Using Typescript to identify the specific subtype of an object within a union type based on the properties it contains

I am trying to create a carousel that displays items of two different types (FirstType, SecondType). The carousel component I am using requires an array as input, so I have declared the items as an array union like this: type FirstType = { a: 'first ...

Retrieve recently appended DOM elements following the invocation of createComponent on a ViewContainerRef

I have a current function in my code that dynamically creates components and then generates a table of contents once the components are added to the DOM. This service retrieves all h3 elements from the DOM to include in the table of contents: generateDy ...

Achieve top-notch performance with an integrated iFrame feature in Angular

I am trying to find a method to determine if my iframe is causing a bottleneck and switch to a different source if necessary. Is it possible to achieve this using the Performance API? This is what I currently have in my (Angular) Frontend: <app-player ...

Express and Angular2 Webpack integration

Recently, I set up Angular 2 with Webpack and explored its routing capabilities through a sample app. I am now interested in integrating Angular2 for front end routing while utilizing ExpressJS for a RESTful API backend on the same server. For example, ht ...

Retrieve: Type 'string | undefined' does not match the parameter type 'RequestInfo'

When using the fetch function, I encountered an error with the "fetchUrl" argument: Error: Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'. This is the code snippet where the error occurred: ...

How to attach an event listener to an input element using Angular

I am looking to add a listener to an input element that will be triggered every time the user changes the input values. The goal is to display the current values chosen by the user. Example HTML template: <div id="idDoseLabel1" class="da ...

`ionic CapacitorJS extension for Apache server`

Currently, we are developing a hybrid mobile app using Ionic Capacitors. In the initial stages, we started with an Ionic Cordova project and then upgraded it to an Ionic Capacitor project using the latest version. For network requests, we utilized the fol ...

Exploring the process of linking MatPaginator to a server-sourced datasource within an Angular Material table

In my Angular 5 project, I am utilizing Angular Material table to create a grid. The data is fetched from an HTTP request and stored in a variable named dataSourceNew within the view.ts file. Since dataSourceNew has dynamic content and structure, no interf ...

Form for creating and updating users with a variety of input options, powered by Angular 2+

As I work on creating a form, I encounter the need to distinguish between two scenarios. If the user selects 'create a user', the password inputs should be displayed. On the other hand, if the user chooses to edit a user, then the password inputs ...