Tips for retrieving items from <ng-template>:

When the loader is set to false, I am trying to access an element by ID that is located inside the <ng-template>. In the subscribe function, after the loader changes to false and my content is rendered, I attempt to access the 'gif-html' element but it returns null.

<div class="my-loader" *ngIf="loader; else show_form_content">
    <ngx-loading [show]="loader"></ngx-loading>
  </div>
  <ng-template #show_form_content>
   <div class="gifTimer" id="gif-html">
 
   </div>
  </ng-template>
 
 </div>

 getMyData() {
  this.loader = true;
  this.myService
    .getData()
    .subscribe((response) => {
      this.loader = false;
      if (response.status === 'success') {
        let gifHtml = document.getElementById('gif-html');
        console.log('gifHtml', gifHtml)
      }
    });
}

ngOnInit(){
  this.getMyData()
}

Answer №1

When the getElementById method returns null, it could be because the ng-template content has not yet been rendered in the DOM.

The ng-template behaves as a structural directive and does not immediately render its content. It acts as a template that can be conditionally displayed using directives like *ngIf or *ngTemplateOutlet.

HTML

<div class="my-loader" *ngIf="loader; else show_form_content">
  <ngx-loading [show]="loader"></ngx-loading>
</div>

<ng-template #show_form_content>
  <div class="gifTimer" id="gif-html">
 </div>
</ng-template>

To address this issue, I have included the id="gif-html" template reference variable within the div element.

import { ViewChild, ElementRef, AfterViewInit  } from '@angular/core';


export class YourComponent {
  @ViewChild('gif-html', { static: false }) gifHtmlRef!: ElementRef;

    ngAfterViewInit() {
      this.getMyData();
    }

    getMyData() {
        this.loader = true;
        this.myService
          .getData()
          .subscribe((response) => {
            this.loader = false;
            if (response.status === 'success') {
              console.log('gifHtml', this.gifHtmlRef.nativeElement);
            }
        });
    }
}

I hope this information proves helpful.

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

Encountered a problem while rendering the app: [TypeError: Unable to assign a value to the property 'content' since it is undefined]. Implementing Express with

My experience with res.render is flawless: res.render('main', function(err, html){ // Displays '<html></html>' from 'views/main.html' console.log(html); }); However, the situation changes when it comes to ...

Disable image loading for users who have javascript enabled

I find myself caught in a chicken-egg dilemma. The webpage I created contains numerous images that need to be loaded, and so I implemented a script that loads images as the user scrolls, similar to how Facebook or Google Images functions. When the user rea ...

Angular does not receive events from Socket.io

Recently I started coding with AngularJS and decided to build a real-time app using Socket.io: The service I'm using shows that the connection is fine on the console. Here's a picture of the Console.log output However, when I attempt to emit c ...

Establish map boundaries using the longitude and latitude of multiple markers

Utilizing Vue, I have integrated the vue-mapbox component from this location: I've made sure to update the js and css to the latest versions and added them to the index.html: <!-- Mapbox GL CSS --> <link href="https://api.tiles.mapbox.com/m ...

Managing variables or properties that are not defined in ES6

Currently, I am utilizing Angular and Firebase Firestore in my project. However, the question posed could be relevant to Typescript and pure Javascript as well. The functionality of my application relies heavily on the data retrieved from Firestore. A sim ...

Utilize the <wbr> tag within FormattedMessage and assign it as a value while coding with TypeScript

Trying out the optional word break tag <wbr> in a message within <FormattedMessage id="some:message" />. Context Some words or texts are too lengthy for certain parent elements on smaller mobile screens, and we have a column layout t ...

How shouldjs makes value verification effortless for unordered arrays

In my express.js application, I'm currently using supertest and should.js as my preferred testing framework. However, I've encountered some difficulties when it comes to testing for specific values within an unordered array. After referring to t ...

Slide the next section over the current section using full-page JavaScript

I'm currently developing a website utilizing the FullPage.JS script found at this link . My goal is to have the next section slide over the previous one, similar to what is demonstrated in this example. I've attempted setting the position to fix ...

Run an npm script located in a different package

Imagine I have two node packages, one named parent and the other named child. The child package contains a package.json file with some scripts. Is it viable to merge the scripts from child into the context of parent? For instance: child/package.json: "s ...

A guide on utilizing getStaticProps to map a collection obtained from Strapi within a Next.js component

I'm currently following a tutorial on YouTube that teaches how to create a basic blog using Next.js and Strapi. The code snippet below is used to fetch post data from Strapi, but it's not working as expected because the .map function can only be ...

`What can be done if ng-if is not responding?`

I'm facing an issue where I want to display a link <a href> only when a certain condition is met, but the link doesn't show up as expected. I have already attempted to experiment with changing the position of the code (inside or outside of ...

Retrieving Information from an API with Custom Headers in React Native

I have an API that necessitates specific headers for access. Without these headers, a browser displays the following error: Code: 4101 Message: Header X-Candy-Platform is required However, when the headers are provided, the API returns a json response. ...

Expanding Arrays through Functional Inheritance

Through the concept of functional inheritance, objects can be extended by using them as the context for a function call and assigning to this. However, this approach does not seem to work as expected when dealing with the Array constructor. var ctx = { ...

Implementing child components in React using TypeScript and passing them as props

Is it possible to append content to a parent component in React by passing it through props? For example: function MyComponent(props: IMyProps) { return ( {<props.parent>}{myStuff}{</props.parent>} } Would it be feasible to use the new compone ...

What is the purpose of setting the Z-Index on a Popper menu

If you want to see a live example demonstrating the issue, head over to codesandbox.io. My goal is to create a 'sit below' menu just like it's shown in the Material-UI documentation here. return ( <div className={classes.root}&g ...

The React Material-UI Slider does not move when OnChangeCommitted is triggered

Struggling with implementing the Material UI slider in React, I encountered an issue where the OnChange function would trigger every time the value changed. I needed it to activate only when the left mouse button was released. Fortunately, I discovered a s ...

What could be causing render_template to fail when attempting to update the same parameters more than once?

Lately, I've dived into the world of Flask, MongoDB, and ElasticSearch. So far, my MongoDB and ElasticSearch setups are running smoothly. However, I've encountered an issue with generating a list of dictionaries and displaying them on my HTML we ...

In Angular's production build on Webkit/Safari, the left-hand side of the operator '=' must be a reference

Recently, I completed a project using Angular. After successfully building it for production without any errors, everything seemed to work perfectly on Chrome. However, when attempting to run the app on Webkit/Safari, an error was displayed in the cons ...

What is the purpose of employing this expression in the context of requestAnimationFrame?

Can you explain the purpose of using this specific "if" statement in relation to requestAnimationFrame? if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime ...

Building paths through a jQuery loop

Transform String into Delimited Array, Generate Loop of Check Boxes, and Build New String Given String = "Folder Tier1\Folder Tier2\Folder Tier3\Folder Tier4\Folder Tier5\Folder Tier6\" (Missing) Use "\" as a delimi ...