KaPaHgaIII KaPaHgaIII - 3 months ago 52
TypeScript Question

Highlight recently created by*ngFor element in Angular 2

I have a list of

Word
s, shown or hidden by
*ngFor
according to their
hidden
property.

Please check plunker.

The problem is that when there are a huge amount of words in list, it is difficult to find where the new one appeared. So I would like to highlight them.

My idea was to set a
.highlight
class by default and to remove it after item was added, with smooth
transition
:

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;
}


Unfortunately this doesn't work, as new item is already created without
.highlight
class.

So, here is the question: how to detect when a new item was added and which item exactly was added? Is it even possible? Or may be there is another way to achieve what I want?

P. S. please tell me if I attached incorrect plunker or something else wrong with my question.

Solution



First of all sorry for incomplete description, I forget to mention that I want to switch off a hightlight after a while.

Please check @Boyan Kostadinov's answer and then return here for a final solution and final plunker:

new
toggleHidden()
:

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

Answer

This will get you what you want: http://plnkr.co/edit/QxvCte7SvYg3hljBPIlB?p=preview

Explanation:

Added new "highlighted" property to your words class:

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

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

Changed the toggleHidden function:

@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, highlihted: item.highlihted}">
         {{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.highlihted = false });

    item.hidden= !item.hidden;
    if (!item.hidden) item.highlihted = true;
  }
}