When ngIf fails to detect a change in a variable's value

Whenever I try to set a simple boolean variable to show/hide a div from another component, the ngIf directive doesn't seem to recognize it.

In my messages-refresh.component.html file:

<div class="divOpacity" *ngIf="show">
<div class="boxMessageModal">
    <p>New data has been found for this page, click Ok to refresh!</p>
    <button class="btnOktoReload" (click)="reloadPage()">Ok</button>
</div>

In my messages-refresh.component.ts file:

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';

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

export class MessagesRefreshComponent implements OnInit {

  constructor(private location:Location) { }

  reloadPage(){
    location.reload(true)
  }

  show:boolean = false
  showDivOpacity(){
    this.show = true
  }

  ngOnInit() {
  }

}

To trigger the showDivOpacity method from another component, use

this.messagesRefreshComponent.showDivOpacity()

Answer №1

Each instance is different because you are attempting to utilize injection with a component.

To resolve this issue, consider using an injection class singleton with a BehaviorSubject. This approach will provide a single instance with storage for saving objects or values, accessible by all components through injection.

import { Injectable, OnInit } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable()
export class SettingsService {
  private showSubject = new BehaviorSubject<boolean>(false);

  setUpdateShow(){
      this.showSubject.next(!showSubject.getValue());
  }

  isShowing$(){
     this.showSubject.asObservable();
  }
}

Subsequently, in the components, you can inject and use the value.

The Component.ts displaying the subject

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';

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

export class MessagesRefreshComponent implements OnInit {

  constructor(private settingsService:SettingsService ) { }
 show$: Observable<boolean>()
 ngOnInit() {
   this.show$ = this.settingsService.isShowing$();
 }
}

HTML

<div class="divOpacity" *ngIf="show$ | async">
<div class="boxMessageModal">
    <p>New data has been found for this page. Click Ok to refresh! </p>
    <button class="btnOktoReload" (click)="reloadPage()">Ok</button>
</div>

To access or modify the subject, you need to inject the services and call the setUpdateShow() function. This may be a bit complex to grasp at first, but it is the optimal solution for communication between unrelated components.

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

Connection to mongo is currently unavailable for Middleware next

This code snippet shows a middleware for Next, which is designed to read the subdomain and check if it exists in the database. import { getValidSubdomain } from '@/lib/getValidSubdomain'; import { NextResponse } from 'next/server' impor ...

The group validator has no effect on the form's isValid status

After working with form groups in angular 5, I noticed that setting a group validator like this: this.myForm = formBuilder.group({ control1: [null, [Validators.required, Validators.minLength(3)]], control2: [null, [Validators.required, Validat ...

Making Amazon Cognito function seamlessly with angular2 and typescript

Having trouble getting Cognito’s Forgot password feature to work Using: Angular2+Typescript+Ionic New to this process, followed a Quickstart guide I found here No matter what I try, keep getting errors like Cannot read property 'CognitoUser' ...

Automatically activate the Focus Filterfield in the ng-multiselect-dropdown upon clicking

I've integrated the ng-multiselect-dropdown package into my Angular project using this link: https://www.npmjs.com/package/ng-multiselect-dropdown. Everything is functioning as expected, but I'm looking to automatically focus on the filter input ...

Automatic renewal of bearer token in Angular 7

My AuthService has two key methods: getAuthToken (returns a Promise to allow lazy invocation or multiple invocations with blocking wait on a single set) refreshToken (also returns a Promise, using the refresh token from the original JWT to request a ...

What is the default appendTo value in ng-select for Angular 10 and above?

I have encountered a problem where I am utilizing the same component on both a modal and a regular page. <ng-select [items]="obs$ | async" [appendTo]="body" > </ng-select> While this setup works fine for the regular page, t ...

Angular: The CORS issue continues despite configuring proxy.conf.json

I have tried several tutorials in an attempt to resolve my CORS issues, but unfortunately, I have been unsuccessful so far. My server setup is very basic - it responds to get 127.0.0.1:8080/hello by returning the string hello there for testing purposes. ...

Testing a function within a class using closure in Javascript with Jest

Currently, I am attempting to simulate a single function within a class that is declared inside a closure. const CacheHandler = (function() { class _CacheManager { constructor() { return this; } public async readAsPromise(topic, filte ...

Anticipating outcome in NgRx Effects

Incorporating ngrx-effects into my project has been successful for retrieving data: component dispatches action -> effect triggers http service call -> data is returned from http service -> effect sends data to store through action -> component ...

Leveraging the power of NestJS in conjunction with Apollo Server version 2

I recently delved into learning nestjs and decided to give this graphql example a try. The issue I encountered is that the example was originally designed for apollo-server version 1, and I'm having difficulty adapting it to work with apollo-server v ...

Unraveling the art of utilizing the map operator in ES6 with condition

I need to implement a condition within the map function where I prepend zeros for single digit values (00.00 to 09.30), while leaving remaining values unchanged. Currently, it is prepending zeros for all values. Here is the code: export class SelectOver ...

Angular 10 encountering issues with loading Bootstrap styles

I'm currently working on a project that involves Angular 10 and the Bootstrap library. However, I'm encountering an issue where the Bootstrap styles are not loading properly. Upon checking the package.json file, I can see that Bootstrap is liste ...

Arrangement of code: Utilizing a Node server and React project with a common set of

Query I am managing: a simple react client, and a node server that functions as both the client pages provider and an API for the client. These projects are tightly integrated, separate TypeScript ventures encompassed by a unified git repository. The se ...

The 'forkJoin' feature is not available within the Observable class

I am experiencing issues with the old method of importing forkJoin, and I keep encountering this error message. What is causing this error to occur? import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/comm ...

Issue: Dependency type ContextElementDependency does not have a corresponding module factory available

After cloning the project from GitLab and running npm install, all dependencies were successfully downloaded. However, upon executing npm start, I encountered an error stating "No module factory available for dependency type: ContextElementDependency." In ...

How can we efficiently link data to custom objects (models) within a different class while fetching data from the server using the http.get() method in Angular CLI?

Currently in the process of developing an Angular-Cli application that involves multiple models with relational data tables. When fetching data from the server, I need to map this data to corresponding model objects. I've experimented with creating a ...

Ensure that the constructor function is fully executed before triggering the interceptor function

As a beginner in Angular, I decided to utilize Firebase for storing user tokens that can be retrieved when calling an interceptor to modify request headers. I have included the firebase function in the constructor and the HttpHandler function separately, ...

Issue with resolving parameters for AppComponent in Angular 6

Currently in the process of constructing an application using Angular 6, while still in the setup phase. Encountering difficulties with dependency injection within my application. The app is unable to resolve any constructor parameters resulting in Uncaug ...

Issues with manipulating state using TypeScript Discriminated Unions"Incompatibility with setState

Imagine having a unique type structure like the one shown below: export type IEntity = ({ entity: IReport setEntity: (report: IReport) => void } | { entity: ITest setEntity: (test: ITest) => void }); Both the entity and setEntity fun ...

Having trouble building a new project with Angular-cli v.6?

I recently installed Angular CLI version 6 and created a new project following these steps: npm install -g @angular/cli@^6.0.0 ng new my-app cd my-app npm install npm build However, I encountered an error during the build process with the following messa ...