Charles Webb
Charles Webb

Reputation: 45

How to change class of individual elements inside ngfor?

I'm very sorry if this question has been answered however I was unable to find an appropriate answer. I am attempting to create a simple chat application and wish for messages sent by the current user to appear on the right hand side of the screen whilst messages from other users will appear on the left.

I believe I am most of the way there with this however its not functioning properly, if the most recent message is sent by the current user then all the message will be on the right vica versa for messages from other users.

My question in more detail therefor is, is there a way for me to change the class for a list item that is generated by ngFor, with each element possibly having a different class to any other list item.

Below is the HTML:

    <ion-item *ngFor="let message of messages; let i = index" (click)="beingWhisper(message)">

    <ion-card [ngClass]="styleClass">
      <ion-card-header class="messageHeader">
        {{i}}{{message.Person}}
      </ion-card-header>
      <ion-card-content>
        {{message.Message}}
      </ion-card-content>
    </ion-card>

</ion-item>

Here is the very basic CSS:

.message-other{
  float: left;
  width: 50%;
}
.message-self{
  float: right;
  width: 50%;
}

The ngClass variable is controlled simply with this variable on my component class, this is changed to be either "message-self" or "message-other" when required

    styleClass = '';

Fixed: In case anyone finds this question with a similar problem, my issue was fixed by using the individual messages property, which held the senders ID and if it was the same as the current user ID then apply the style I wanted, this was discovered through dfsq's suggestion, with thanks to Günter Zöchbauer as his suggestion was also correct

Upvotes: 2

Views: 3441

Answers (1)

dfsq
dfsq

Reputation: 193271

What you should do in cases like this is to compare currently authenticated used id with message id, which should be a sender used id. Then you ngClass look something like this:

[ngClass]="message.userId === currentUser.id ? 'message-self' : 'message-other'"

Upvotes: 4

Related Questions