Display and conceal multiple div elements using Angular 2/Typescript after a brief delay

Currently, I am in the process of generating multiple divs while passing specific data to them. My objective is to hide certain divs based on particular conditions.

However, the issue I am facing is that all divs are being hidden regardless of the conditions that are set.

For instance, if I set "on: true" for one div, it ends up hiding all the divs. This might be due to the forEach loop that I am executing on all elements, but I am uncertain about how to resolve this problem.

Below is my TypeScript code:

export class ShowDataComponent implements OnInit {
@ViewChildren('notification') private el:  QueryList<ElementRef>;
        this.showData= arrayData;

ngAfterViewInit() {
for (let i = 0; i < this.showData.length; i++){
  this.on = this.showData[i].on;
  this.duration = this.showData[i].duration;
  if(this.on){  
this.el.forEach((element)=>{      
  const htmlElement = element.nativeElement as HTMLElement;
  setTimeout(() => htmlElement.setAttribute("style", "display:none;"), this.duration);
});
  }
}
}
}

And here is my HTML code:

<div *ngFor="let n of showData">
  <div #notification class="show-top-bar" style="display: block;">
      {{n.message}}
  </div>
</div>

Answer №1

The reason all divs are hidden is due to the placement of the forEach function right after if(this.on){. This setup necessitates that at least one element in the showData array must have the on property set to true in order for any divs to be displayed.

Answer №2

It's important to remember that the DOM manipulation should be left to the framework, as that is its designated task. Without utilizing the framework, the purpose of having one is diminished.

Reviewing your code, it appears that you have not declared an on class member, and the code is set to hide all divs.

Based on the context, it can be assumed that there is a condition on the elements referred to as on, as it aligns most closely with what is expected.

To begin with your HTML code:

<div *ngFor="let n of showData">
  <div *ngIf="n.on" class="show-top-bar" style="display: block;">
      {{n.message}}
  </div>
</div>

Initiate by applying the condition to the on property of the element. Then, set all values to true for displaying them, and generate an array of values for later usage:

constructor() {
  this.referenceArray = this.showData.map(n => ({id: n.id, on: n.on}));
  for (let n of this.showData) {
    n.on = true;
  }
}

Subsequently, reset all properties to their initial values after a delay:

ngAfterViewInit() {
  setTimeout(() => {
    for (let n of this.showData) {
      n.on = this.referenceArray.find(rn => rn.id === n.id).on;
    }
  });
}

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

Explaining the data link between a service and component: understanding Subject and BehaviorSubject

Can someone explain the concepts of Subject and BehaviorSubject in Angular to me? I'm new to Angular and struggling to understand. I've tried searching online, but I still can't grasp how they work. The same goes for Observable and Observer ...

I'm currently in a situation where I'm trying to update a dependency, but it seems that

I am currently facing a challenge updating Angular from version 12 to version 16. My goal is to integrate the three.js library into my project, which requires Angular CLI version 16 or higher. Although I have successfully updated angular/cli to version 1 ...

Angular 5 failing to navigate to new page upon successful login

Implementing an authentication system using Angular 5 that utilizes Tokens has been my recent project. However, I encountered a hurdle while trying to authenticate on the login-form - it initiates the process but ends up refreshing the page instead: View ...

Error in Typescript due to delegate function not being recognized post minification

Here is a code snippet that uses delegate: <pre> $.ajax(this.validateURL, { type: "post", url: this.validateURL, data: JSON.stringify(i), contentType: "application/json; charset=utf-8", dataType: "json", success: i => t.pro ...

Working with objects in *ngFor in Ionic 2

I am utilizing Ionic 2 and attempting to display the content of a key-value array using an object. In order to display my collection, I am using a pipe in my HTML. Below is my HTML code: <ion-list> <ion-item *ngFor="let event of this.pdata. ...

Acquire information using AngularJS

This is a demonstration of my service: import { Injectable } from '@angular/core'; import { GenericPostService } from 'app/shared/services/generic.post.service'; @Injectable({ providedIn: 'root' }) export class FaqServic ...

Access User Authentication Profile Information in Firebase Utilizing Angular 2

Need assistance with retrieving user profile information from Angularfire Authentication in Angular? Specifically looking to access the user's Facebook profile picture and name. Your help would be greatly appreciated. Thank you! I have attempted the ...

Guide on invoking personalized server-side functions (such as object parsing) utilizing Typescript and Angular tools

I've been grappling for weeks to make custom service calls function with Typescript / Angular / C#. It's been a challenge to find a workable solution online, and the more I search, the more bewildered I become. My current approach has largely be ...

When selecting a different file after initially choosing one, the Javascript file upload event will return e.target as null

Currently, I have implemented file uploading using <input>. However, when attempting to change the file after already selecting one, the website crashes and states that event.target is null. <Button label="Upload S3 File"> <input ...

Encountering an error message about 'resolving symbol values statically' while building an Angular 2 project

Currently, I am utilizing an older module called angular-2-local-storage. The initialization process is as follows: const LOCAL_STORAGE_SERVICE_CONFIG_TOKEN: string = 'LOCAL_STORAGE_SERVICE_CONFIG'; export const LOCAL_STORAGE_SERVICE_CONFIG = ne ...

The Bootstrap CSS styles seem to be malfunctioning following the upgrade from Angular 4 to Angular 5

Developed a Single Page Application with Angular 4 and .NET Core 2, integrated with Bootstrap for styling. However, upon upgrading from Angular 4 to Angular 5, the Bootstrap styling disappeared. It seems that the bootstrap.css file is not being loaded cor ...

Turning ngIf from false to true upon clicking the back button

I added an ngIf directive to hide a button on click and then move on to the second component. In the second component, I included a back button to return to the first component. However, when I click "back" to go to the first component, the ngIf remains fa ...

Step-by-step guide on integrating a custom JS file into an Angular component

Trying to grasp Angular, I embarked on adding some JavaScript logic to one of my components from a separate JS file. While following advice from a similar query (How to add custom js file to angular component like css file), it seems I missed something cru ...

Angular 8 encountering issues with incomplete/impartial JSON parsing

Upon receiving a JSON object through a Socketio emit, the data appears as follows: { "single":[ { "name":"Xavi555", "data":[ { "_id":"5e2ea609f8c83e5435ebb6e5", "id":"test1", "author":"someone", ...

Move the cache folder for NextJS to a new location

Is it possible to customize the location of the cache folder currently located in "./.next/cache"? I am interested in modifying this because I am developing an application that receives high traffic daily, and I plan to deploy multiple applications from m ...

What is the correct way to submit a formarray in an angular application following the specified format?

When submitting a form in Angular, I'm facing an issue where only the data from the first index inside the role menu is being passed. How can I ensure that all index data is passed on submit? { "roleMenu":[{ "menu":{ "menuId": 1 }, ...

Different parameters in an Angular filter pipe

Currently, I am facing a challenge in implementing multiple filters on a pipe for a search result page that retrieves data from an API. How can I integrate different parameters into this filter pipe successfully? Access the application here: https://stack ...

Understanding the significance of the add() operator in RxJS

Can someone clarify the purpose of the add() operator in rxjs? I've seen it mentioned that it includes a teardown function, but there isn't much detail on what exactly a teardown is or why it's necessary. My specific query relates to impleme ...

Utilizing a personalized directive within a ionic popup

I am currently using the ion-textarea autosize directive: import { Directive, HostListener, ElementRef } from '@angular/core'; @Directive({ selector: 'ion-textarea[autosize]' }) export class AutoResizeTextareaDirective { readonly ...

Unable to bring in the specified export 'Directive' from a non-EcmaScript module - only the default export is accessible

I am currently working on an ionic angular project and utilizing the ng-lazyload-image plugin. However, I am encountering errors during compilation that look like this: Error: ./node_modules/ng-lazyload-image/fesm2015/ng-lazyload-image.mjs 401:10-19 Can ...