Spotlight a newly generated element produced by the*ngFor directive within Angular 2

In my application, I have a collection of words that are displayed or hidden using *ngFor based on their 'hidden' property.

You can view the example on Plunker.

The issue arises when the word list becomes extensive, making it challenging to identify newly added words. To address this problem, I want to implement a highlighting feature for new items.

My approach was to assign a default '.highlight' class and remove it once an item is added with a smooth transition effect:

HTML

<div 
   *ngFor="let item of words | shownWords" 
   [ngClass]="{'item':true, 'highlihted': item.hidden}">
   {{item.value}}
</div>

CSS

.item {
    background-color: #ffffff;

    transition: background .3s ease-out;
    -moz-transition: background .3s ease-out;
    -webkit-transition: background .3s ease-out;
    -o-transition: background .3s ease-out;
}
.item.highlihted {
    background-color: #ea90aa;
}

However, the above method does not work as the new item is created without the '.highlight' class.

Thus, my question is: Is there a way to detect when a new item is added and specifically identify which item it is? Is this even achievable, or is there an alternative solution?

P.S. Please let me know if I provided an incorrect Plunker link or any other issues in my question.

Solution

Apologies for missing information earlier, but I also intend to remove the highlight after a certain period.

Refer to @Boyan Kostadinov's answer first and then come back for the final solution and final Plunker:

New method toggleHidden():

toggleHidden(item: Word) {
    item.hidden = !item.hidden;
    if (!item.hidden) {
        item.highlihted = true;
        setTimeout(() => {
           item.highlihted = false;
        }, 500);
    }
}

Answer №1

Here is the solution to your issue: http://example.com/solution

Here's a breakdown of what was changed:

The "highlighted" property was added to the words class:

export class Word {
    value:string;
    hidden = false;
    highlighted = false;

    constructor(value: string) {
        this.value = value;
    }
}

The toggleHidden function was updated:

@Component({
  selector: 'my-app',
  pipes: [ShownWords],
  template: `

      <h2>Click on a word above line to show/hide word below line:</h2>
      <div *ngFor="let item of words" (click)="toggleHidden(item)">{{item.value}}</div>
      <hr>
      <div 
         *ngFor="let item of words | shownWords" 
         [ngClass]="{item:true, highlighted: item.highlighted}">
         {{item.value}}
      </div>
  `
})
export class AppComponent { 
  words: Word[] = [new Word('one'),new Word('two'),new Word('three'),new Word('four'),new Word('five')];

  toggleHidden(item:Word) {
    this.words.forEach((w:Word) => { w.highlighted = false });

    item.hidden= !item.hidden;
    if (!item.hidden) item.highlighted = 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

Delete an essential attribute from an entity

I am trying to remove a required property called hash from an object, but I keep encountering TypeScript or ESLint errors. All the properties of the interface are mandatory, and I do not want to make all properties optional using Partial. Here is the inte ...

What is causing the failure of this polymorphic assignment within a typed observableArray in Knockout?

Consider a scenario where we have a class A and its subclass B. The goal is to assign an array of instances of class B to an array of instances of class A. While this works with normal arrays, the same operation fails when using ko.ObservableArray. import ...

What is the process for declaring a module in order to perform named imports?

Currently, I am utilizing graphql-tag in my project. The structure of my files is as follows: ./operation.graphql Query User { ... } ./test.ts import { User } from './operation.graphql'; /// Module ''*.graphql'' has no ...

What is the best way to retrieve the targeted style directly from CSS, rather than relying on the computed style of the element?

Although similar questions have been posed before, such as this one, I haven't found a working solution. Is there a way for me to retrieve the width attribute value from a CSS class and then write it to a div? I'm looking to access the exact va ...

import component dynamically from object in Next.js

Currently, I have a collection of components that I am aiming to dynamically import using next/dynamic. I'm curious if this is achievable. Here's the object in interest: // IconComponents.tsx import { Tick, Star } from 'components ...

What is the best way to display a JSON array in Angular 4?

Check out this JSON structure: -------------------------------------------------- "id": 2, "user": { "id": 1, "name": "User", "surname": "User", "email": "<a href="/cdn-cgi/l/email-protection" ...

Customize Tab indicator styling in Material-UI

Currently, I am attempting to customize the MUI tab by changing the indicator from a line to a background color. Through my research, I discovered that using TabIndicatorProps and setting a style of display:none eliminates the indicator completely. However ...

What are the steps to stop the left alignment of header text?

As I'm working on designing a unique Markdown theme in CSS, I am currently facing some challenges with regards to the styling of headers. Specifically, the h1 header is styled as follows: h1 { border-top: 1px solid black; width: 10%; margin: 0 ...

Implement a back-to-top feature with a scroll button (Ionic 2 | Typescript)

Hello, I am currently working on incorporating a "scroll to top button" feature that includes the following requirements: Display the button once the user has scrolled down. Hide the button when the user scrolls back up. If the button is clicked ...

Steps to resolve the error "The value for '--target' option should be one of the following: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es201', 'esnext'."

I recently cloned an Angular application and encountered an error related to the "target" property in the tsconfig.json file within Visual Studio 2019. My Angular version is v16.1.4, with Typescript v5.1.6. I've attempted to resolve this issue by upda ...

Encountered a problem while installing an npm package for Angular 2

I seem to be encountering an error when trying to run the npm install command in the command prompt behind my corporate proxy firewall. Previously, I was able to edit the npm file with the proxy settings, but now I receive this error no matter what npm com ...

Tips on concealing all classes except one through touch swiping

If you have a website with a single large article divided into multiple sections categorized as Title, Book1, Book2, & Book3, and you want to implement a swipe functionality where only one section is displayed at a time, you may encounter some issues. ...

I am experiencing issues with the functionality of the Search Button in my code

I am experiencing an issue with the Search Button in my Search Form. I created the Search form using only html and pure CSS to test whether JS is necessary for a Search form with Drop Down Filter! Do I need to incorporate some JS code or is it feasible to ...

Sveltekit: Troubleshooting problem of refreshing when utilizing store and localStorage

I am currently working on persisting data using localStorage and have successfully achieved persistence. However, I notice that when I refresh the page, it initially displays a value of 0 before fetching the localStorage value. Is there a way for me to ins ...

Encountered an issue when trying to generate a shader cache entry- there was an error when attempting to locate an

Today, I decided to write a basic Python script utilizing Selenium that would identify an element by its Css selector. My target? The input field on the Google webpage, specified by input[name=q] Upon running the script, Chrome opened as expected but prom ...

My a:hover isn't functioning properly and my <a> tag is not redirecting to the link when clicked. Can anyone help me troubleshoot these issues?

I've created a website with multiple stacked sections. Each section is contained within a div with the class class="concertDiv". In one of these sections, I want to display an album cover on the left side and three clickable text rows on the right sid ...

Encountering a 404 error for core.js and browser.js while loading an Angular 2 app through system.src.js

I am new to Angular2 and have followed the Angular2 quickstart and tutorial to get started. Just to provide some context, when a user clicks on a link in the top navigation bar of my webapp, it triggers a server side request. The resulting page returned t ...

Retrieving the location.host parameter within NgModule

I am currently working on integrating Angular Adal for authenticating my application's admin interface with Azure AD. However, I have encountered a challenge with the redirectUri setting. My goal is to dynamically retrieve the current app's host ...

Verify if the transaction is present in rxjs

private transactions = new BehaviorSubject([]); getTransactions(): Observable<ITransaction[]> { return this.transactions.asObservable(); } checkTransactionsExist():Observable<boolean> { return this.getTransactions().pipe ...

Guide to linking properties to Bootstrap 5 components within Angular

I am currently using Angular 13 along with Bootstrap 5. The bootstrap elements are functioning perfectly fine for static content. <button type="button" class="btn btn-lg btn-danger" data-bs-toggle="popover" title="Popo ...