Highlighting DOM elements that have recently been modified in Angular

Is there a simple way to change the style of an element when a bound property value changes, without storing a dedicated property in the component?

The elements I want to highlight are input form elements:

    <tr field label="Lieu dépôt">
        <select class="cellinput" #lieuDepotBon [(ngModel)]="rapport.LieuDepotBon" (ngModelChange)="changeRapport({LieuDepotBon:$event})">
            <option [ngValue]="null"></option>
            <option [ngValue]="i" *ngFor="let depotBonChoice of DepotBonInterventionValues; let i = index">{{DepotBonIntervention[i]}}</option>
        </select>
    </tr>
    <tr field *ngIf="rapport.LieuDepotBon==DepotBonIntervention.Autre" label="Autre lieu">
        <input class="cellinput" #autreLieuDepotBon [(ngModel)]="rapport.AutreLieuDepotBon" (ngModelChange)="changeRapport({AutreLieuDepotBon:autreLieuDepotBon.value})" />
    </tr>

I have heard about special class styles set by Angular2 on elements with ngModel directive that might help achieve what I need, but I haven't been able to find more information about it.

Answer №1

A simple and efficient solution would be to create two CSS classes for highlighting styles:

.custom-highlight{
    background-color: #FF0;
}
.remove-highlight{
    background-color: #AD310B;
    -webkit-transition: background-color 1000ms linear;
    -ms-transition: background-color 1000ms linear;
    transition: background-color 1000ms linear;
}

You can then apply these classes in sequence to the element as needed. I hope this suggestion proves helpful!

Answer №2

Here is the approach I took.

I aimed to emphasize the data in the Form that gets modified by other users in real-time.

To achieve this, I opted to replace native html elements in my HTML form with Angular components. For each type of native element, I designed a new Angular Component equipped with Highlight functionality. These components all implement the ControlValueAccessor Angular interface.

In the parent form, I swapped out the native element:

<input [(ngModel)]="itinerary.DetailWeather" />

with my custom element:

<reactive-input [(ngModel)]="itinerary.DetailWeather"></reactive-input>

Whenever Angular triggers detectChanges() for the parent form, it scrutinizes all the data inputs utilized by the form's components.

If a component serves as a ControlValueAccessor and an alteration transpires in the application model, it invokes the ControlValueAccessor.writeValue( value ) method. This method is invoked when there is a change in the data in memory. I utilized it as a means to momentarily update the style and incorporate the highlight.

The following snippet showcases the custom element. Angular Animations were leveraged to alter the border color and smoothly transition back to the original hue.

// Custom Element Code Here

Answer №3

If you want to briefly highlight a DOM element, one way to do it is by using the setTimeout() function to add or remove a CSS class.

View demo

HTML

<mat-form-field [ngClass]="{'changed': isChanged}">
  <mat-select [(ngModel)]="yourModel" (ngModelChange)="modelChanged($event)">
     <mat-option value="1">1</mat-option>
     <mat-option value="2">2</mat-option>
     <mat-option value="3">3</mat-option>
  </mat-select>
</mat-form-field>

Typescript

isChanged: boolean = false
modelChanged(value) {
   console.log('model changed')

   this.isChanged = true
   setTimeout(() => {
       this.isChanged = false
   }, 1000);
}

CSS

.changed {
    transition: color 0.4s ease-in, text-shadow 0.4s ease-in, background-color 0.5s linear 0s;
    text-shadow: #bbb 2px 2px 2px;
    background-color: #ffffcc;
    color: #BF1722;
}

Note: If your application requires quicker changes, adjust the time in the setTimeout() function to either 0.5s or 0.3s.

Credit goes to Ingo Bürk for raising awareness about this issue

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

I am puzzled as to why I am receiving the error messages stating that [ngForm] is not recognized as a valid property for the form element, and that [ngClass] is not a recognized

I've been working on this code in Angular 14 for a large client project. The standard imports are listed below, along with a snippet of the .html page: import { Component, OnInit, ViewChild } from "@angular/core"; import { FormBuilder, FormC ...

What is the process for configuring PhpStorm to sync with TypeScript tsconfig.json in .vue files?

Vue.js (webpack + vueify) with TypeScript is my current setup. The ts configuration appears to be functioning, but only in .ts files. For instance, in tsconfig.json: "compilerOptions": { "strictNullChecks": false, So strictNullChecks works as expect ...

unable to retrieve information from the redis cache

Attempting to retrieve data from cache using the readData function in the controller file. Encountering an issue where the someVal variable is initially undefined after calling readData, but eventually gets populated with data after receiving a callback ...

When attempting to Dockerize an Angular CLI app, nothing seemed to happen

I attempted to dockerize my Angular application and created a Dockerfile as follows: FROM teracy/angular-cli as angular-built WORKDIR /usr/src/app COPY package.json package.json RUN npm install COPY . . RUN ng build FROM nginx:alpine LABEL author="pleijan ...

The dimensions of the d3 div remain constant despite any modifications to its attributes

In my angular application, I am trying to customize the width and height of div elements in d3 when I select a legend. Strangely, I am able to adjust the width and height of the svg element without any issues. Here is the issue illustrated: https://i.ssta ...

Can you explain to me the significance of `string[7]` in TypeScript?

As I was working in TypeScript today, I encountered a situation where I needed to type a field to a string array with a specific size. Despite knowing how to accomplish this in TS, my instincts from writing code in C led me to initially write the following ...

The ng test option is failing to execute effectively

Attempting to conduct unit tests utilizing Karma and Jasmine through the ng test is proving to be a bit challenging. Upon issuing the following command: ng test --watch=false --code-coverage --main ./src/main/resources/public/scripts/xyz/workspace/commons ...

The 8 x 8 grid I am constructing is functional, however, the issue lies in the fact that the first line only begins with a single # symbol

I am attempting to create an 8 x 8 grid. It's coming together, but the issue is that the first line only starts with one # sign. function print(msg) { console.log(msg); return msg; } let result = ""; for(let i=1; i<=8; i++) { result += ...

jQuery event triggers upon completion of execution

A custom code has been integrated into my project using jQuery. Check out the code snippet below: <script> $("#startProgressTimer").click(function() { $("#progressTimer").progressTimer({ timeLimit: $("#restTime").val(), onFinish ...

Place a vertical slider adjacent to an HTML element on either the left or right side

I'm struggling to bind a range slider to the left or right side of a canvas that displays video. Despite my efforts, CSS seems to be putting up a strong fight. I can handle issues like stretching and slider values, but attaching it to the canvas is pr ...

The color of the sidebar navigation elements remains consistent

Here is the HTML code snippet that I am currently working with: <div class="row"> <div class="col-sm-3 col-md-2 sidebar"> <ul class="nav nav-sidebar" data-ng-controller="NavbarController"> <li class="nav-item" ...

Having trouble with React npm start: 'No chokidar version found' error occurring

After cloning my React-Typescript app on Github Pages and attempting to make some changes, I encountered an issue. Despite running npm install to install all dependencies, when I tried to run npm start, I received the following error message: https://i.st ...

How can I display the top 5 data results after subscribing in Nativescript?

Utilizing this function allows me to retrieve all my data from the web service. public data: Data[]; getall() { this.ws.getalldata().subscribe( data=> { this.data= data; } ); } Here is a ...

Creating a numeric sequence based on the date of a corresponding transaction - a step-by-step guide

INTRO I built an e-commerce app with TypeScript and Sequelize ORM. In the app, I have a table that generates sequential invoice numbers based on the current day. CREATE TABLE `dm_generate_trx` ( `id` int NOT NULL AUTO_INCREMENT, `date` date NOT NULL, ...

Looking to start using WebDriverIO and Typescript with the WDIO wizard? Here's how to get it

I'm in the process of setting up a WebdriverIO project using TypeScript and Cucumber. I followed the steps provided by the wizard, which was pretty straightforward. I opted for Cucumber, TypeScript, and the page object model. This setup created a tes ...

How can Firebase and Ionic be used to customize the password reset template for sending verification emails and more?

I'm facing an issue with firebase's auth templates not supporting my native language. Is there a way to customize the password reset template to also handle verification and email address change emails? ...

Best Practices for Showing JSON Data from MongoDB in an Angular Material Table

Desire I'm trying to extract data from MongoDB and exhibit it in an Angular Material Table. Problem Even though I can view the results of my MongoDB query in the console/terminal, the Chrome browser console indicates that my JSON data has been save ...

python selenium style attribute for element

There is a snippet of HTML that resembles this: <a class="" data-style-name="Black" data-style-id="16360" "true" data-description="null"<img width="32" height="32" I am trying to extract the text "Black" from it and then click on it. However, there ...

Unable to locate component property

When passing props to my component that link to storybook, I encountered an issue where the object I pass in does not map, resulting in the error message: "TypeError: data.map is not a function". I realized that my object is not actually an &qu ...

Step-by-step guide on utilizing jQuery to fade out all elements except the one that is selected

There are multiple li elements created in this way: echo '<ul>'; foreach ($test as $value){ echo '<li class="li_class">.$value['name'].</li>'; } echo '</ul>'; This code will generate the fol ...