Angular: How to temporarily highlight dom elements that have just changed?

Viewed 8599

Before implementing a solution on my own I would like to know if there is a simple manner to change the style of an element (a brief highlight) when the data bound property value has just change.

There are lot of elements in my DOM so I do not not want to store and maintain a dedicated property in component.

My elements to highlight are traditional input form's 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 heard about special class styles set by Angular2 on element with ngModel directive that could help do what I need but I could not find more about it.

3 Answers

To highlight DOM element for a moment, use setTimeout() to add or remove CSS class

check 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 changes in milliseconds then you should reduce the time for setTimeout() to 0.5s or 0.3s as per your application requirement.

Thanks to Ingo Bürk for pointing-out this issue

Related