angular2 ngif does not effectively conceal HTML elements when set to false

In the HTML file, I have the following code:

<p *ngIf="!checklistsready">
  not ready
</p>


<p *ngIf="checklistsready">
  Ready
</p>

And in my TypeScript file, it looks like this:

checklistsready: boolean = false;


constructor(){
     this.fetchChecks();
   }


 fetchChecks(){
   this._checklistService.getAllchecks() //fetch data from http
     .subscribe(
         res=>{
             console.log(res) //this displays the output
                this.checklistsready = true;  
               }

        )

    }

I'm wondering what could be wrong since the page always displays "not ready"?

Answer №1

It is important to avoid putting asynchronous code in a constructor as it could lead to potential issues. A better approach would be to have your component implement the OnInit interface and retrieve your data within the ngOnInit() method.

Answer №2

To solve the issue, it seems like either the service isn't being called or it is resolving outside of an angular event loop. One solution would be to inject ApplicationRef and call tick() on it after setting the list to true. Alternatively, you could add a button and log the value of checklistsready in the click handler to trigger a change detection round.

import { ApplicationRef } from '@angular/core'

In the controller:

checklistsready: boolean = false;

constructor(public applicationRef: ApplicationRef) {
  this.fetchChecks();
}

fetchChecks() {
  this._checklistService.getAllchecks() //fetch data from http
    .subscribe(
      res=> {
        console.log(res) //this displays the output
        this.checklistsready = true;

        // trigger change detection
        this.applicationRef.tick();
      }
    )
}

Answer №3

Consider providing a specific condition in ngIf. For example:

*ngIf="checklistsready !== true"

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

There was an issue encountered while trying to use HTTPS with a self-signed certificate from a

I made the switch to using https for my nodejs server by following these steps: const https = require('https'); const privateKey = fs.readFileSync('sslcert/server.key', 'utf8'); const certificate = fs.readFileSync('sslc ...

Is it possible to add additional text to an input field without modifying its existing value?

I have a numerical input field labeled "days" that I want to add the text " days" to without altering the actual numerical value displayed. <input type="number" class="days" (keyup)="valueChanged($event)"/> Users should only be able to edit the num ...

Angular: Merge two Observables to create a single list and fetch the combined data

I am currently working on creating a function that returns an observable with a list, compiled from several observables. I feel like I am very close to finding the solution because the debugger stops right before displaying the list. Here is my code: ts t ...

Patience required for Angular to retrieve data from API call

I am currently struggling with getting my Donut chart to load properly with data returned from three separate API calls. I have initialized the chart and the API call functions in ngOninit(). However, it seems like my chart is not loading. I understand tha ...

Is it possible to use Firebase auth.user in order to retrieve the signed-in user directly?

As I develop a webapp with NextJS v13.4 and firebase as my backend using the firebase web modular api, I came across a statement in the documentation: "The recommended way to get the current user is by setting an observer on the Auth object." ...

Issue with blueprintjs/core type in JupyterLab Extension after running npm install

Developed a JLab extension and saved it to Git repository. Established a new environment and successfully pulled the code, which was also verified by a friend. Subsequently, included a new react object to the extension and pushed it back to Git in a fresh ...

Having trouble connecting to the API due to the error "No Access-Control-Allow-Origin" in Angular 2

I am new to working with Angular2 and I'm currently facing a challenge in implementing authentication for an app using username and password login credentials. Unfortunately, I keep encountering the error message "No Access-Control-Allow-Origin". htt ...

Tips for testing nested subscribe methods in Angular unit testing

FunctionToTest() { this.someService.method1().subscribe((response) => { if (response.Success) { this.someService.method2().subscribe((res) => { this.anotherService.method3(); }) } }); } Consider the following scenario. ...

Looking to display a single Angular component with varying data? I have a component in Angular that dynamically renders content based on the specific URL path

I have a component that dynamically renders data based on the URL '/lp/:pageId'. The :pageId parameter is used to fetch data from the server in the ngOnInit() lifecycle hook. ngOnInit(){ this.apiHelper.getData(this.route.snapshot.params.pageId) ...

Angular 13 vulnerability alert triggered by loader-utils bug

After updating to Angular version 13, I discovered 5 critical vulnerabilities: loader-utils <=1.4.1 || 2.0.0 - 2.0.3 Severity: critical Prototype pollution in webpack loader-utils - https://github.com/advisories/GHSA-76p3-8jx3-jpfq Prototype pollution ...

"Trouble with import aliases in a create-react-app project using craco: How to fix it

IMPORTANT UPDATE: Following Stackoverflow guidelines and for the convenience of everyone, I have created a concise reproducible example to showcase the bug in question: https://github.com/shackra/stackoverflow-alias-bug UPDATE 2: Just as an additional no ...

Dynamic Mat-select-trigger that automatically adjusts its size to fit the content

Currently, I am experimenting with an Angular Mat-Select that allows multiple selections. To display the selected values in the value field, I have implemented a custom Mat-Select-Trigger. My goal is to enable automatic resizing of the value field (similar ...

Discovering the tab index of a tab header in Angular 4 Material

In my Angular application, I am using a mat-tab component to display tabs dynamically generated from an array. The template looks something like this: <mat-tab-group> <mat-tab *ngFor="let tb of dynTabs"> ...

Any ideas for handling ProtractorJS timeouts while clicking an element?

The Issue at Hand I am currently facing a challenge with clicking a straightforward 'New Booking' button in my Angular 5 Material 2 Application. The code snippet for the button is as follows: <button _ngcontent-c9="" class="mat-menu-item" ma ...

What is the best way to exclude a particular subtype or property?

Is there a way to exclude a specific nested property? Let's take a look at an example. interface ILikes { article: string, page: string, userId: number | string, } interface IUserData { userName: string, isAdmin: boolean, ...data, ...

The alignment of the first and second steps in Intro.js and Intro.js-react is off

There seems to be an issue here. Upon reloading, the initial step and pop-up appear in the upper left corner instead of the center, which is not what I anticipated based on the Intro.js official documentation. https://i.stack.imgur.com/ICiGt.png Further ...

Unlocking the Power of Angular's Default Input Required Validation

Just aiming to utilize the default required validation functionality in HTML. This is the code I've implemented: <form (ngSubmit)="submit()"> <div class="login-container"> <ion-item> <ion-input ...

Handling JSON Data in JavaScript

In the script below, I have a json object that is being processed: $http({ url: '/mpdValidation/mpdValidate', method: "POST", data: { 'message' : mpdData } ).then(function(response) { console.log(response.data ...

Exploring methods for interacting with and controlling structural directives in e2e testing

Background: My goal is to permutation all potential configurations of an Angular2 screen for a specified route and capture screenshots using Protractor from the following link: http://www.protractortest.org/#/debugging. Problem: I am struggling to figure ...

Exploring the Concept of Angular4 Component Nesting and Input Issues

I've taken on the challenge of completing an exercise from the book "Angular From Theory To Practice - Asim Hussain". The exercise involves refactoring an app using Angular CLI instead of having all components in the same file. You can find a sample f ...