Angular 2 Press + ngClass, how to apply ONLY to SELF, but not ALL elements inside ngFor

In Angular 1.x, this following code works the way I want to click and flip a map inside ng-repeat

<div class="card" ng-repeat="let card of cards">
<div class="flipcard" ng-class="{'flipped':isflipped}" ng-click="isflipped = !isflipped">
</div>
</div>

However, in Angular 2, when he clicked, he flipped every "card" inside the ngFor loop ... how to link the ngClass condition to the element itself?

<div class="card" *ngFor="let card of cards">
<div class="flipcard"  [ngClass]="{'flipped': isflipped }" (click)="isflipped = !isflipped;">
</div>
</div>
+4
source share
2 answers

Change it to:

<div class="card" *ngFor="let card of cards">
    <div class="flipcard"  [ngClass]="{'flipped': card.isflipped }" (click)="card.isflipped = !card.isflipped;">
    </div>
</div>
+4
source

Why does it work with AngularJS (1.x)?

ng-repeatcreate a new area for each iterated element, so the property isFlippedis set in the area of ​​repeating elements (unique to each element):

ngRepeat

ngRepeat . , , $index - .

Angular (2+)?

Angular , , isFlipped, , -, .

card :

, , isFlipped card, , . , , card elements, AOT .

/, . " - (...)".

:

, currentCard :

:

export class MyComponent{
    // (...)
    currentCard:Card;
    // (...)
}

:

<div class="card" *ngFor="let card of cards">
    <div class="flipcard"  [ngClass]="{'flipped': card===currentCard }" (click)="currentCard = card">
    </div>
</div>

, card .

, flipped/not flipped , , card

:

export class MyComponent{

    // (...)

    cards: Card=[];
    private flipped: boolean[];

    flip(index:number){
      this.flipped[index]=!this.flipped[index]
    }

    // (...)

}

:

<div class="card" *ngFor="let card of cards: let i= index">
    <div class="flipcard"  [ngClass]="{'flipped': flipped[i] }" (click)="flip(i)">
    </div>
</div>
+2

Source: https://habr.com/ru/post/1649020/


All Articles