How can I use a variable from a function with ngClass?

时间:2018-01-05 03:08:21

标签: angular typescript angular5

Using Angular 4, I'm trying to use ngClass by comparing a variable, sender created in a function and an object from an array, item.sender.

Here is the HTML:

<ion-card *ngFor="let item of items" [ngClass]="{'me': item.sender == sender, 'notme': item.sender != sender}">
  <ion-card-header>
    @{{item.sender}}
  </ion-card-header>
  <ion-card-content>
    {{item.message}}
  </ion-card-content>
</ion-card>

The function with the variable sender is:

send(desc: string) {
  console.log("message:", desc);

  var listkey = this.listKey;
  var user = firebase.auth().currentUser;
  var uid = user.uid;
  var email = user.email;
  var sender = email.substring(0, email.lastIndexOf("@"));

  var messagecontent = {
    message: this.messagecontent,
    sender: sender,
  };

  firebase.database().ref('userlists' + '/' + listkey +  '/' + 'chat').push(messagecontent);
  this.messagecontent = '';
}

Can this by done, and if so, what am I missing?

2 个答案:

答案 0 :(得分:1)

  public  sender:string = '';


   send(desc: string) {
     console.log("message:", desc);
    ... 
      this.sender = email.substring(0, email.lastIndexOf("@"));
    ....

您还可以使用varlet替换所有const

答案 1 :(得分:1)

您可以使用三元方程并申请ngClass

<强> CODE

<ion-card *ngFor="let item of items" [ngClass]="item.sender === sender ? me : notme">
  <ion-card-header>
    @{{item.sender}}
  </ion-card-header>
  <ion-card-content>
    {{item.message}}
  </ion-card-content>
</ion-card>