What is the best way to utilize a variable from a function when using ngClass in Angular?

Currently, using Angular 4, I'm attempting to utilize ngClass by comparing a variable called sender which is created within a function with an object from an array known as item.sender.

Below is the snippet of HTML code:

<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 containing the variable sender looks like this:

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

I'm wondering if this can be achieved and if so, what might I be overlooking?

Answer №1

  private sender: string = '';

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

It is advisable to replace all instances of var with lets and consts in your code.

Answer №2

To implement conditional styling in Angular, utilize the ternary operator within the ngClass directive.

SAMPLE 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with the react event handler for the renderedValue component in Material UI?

I am facing an issue while trying to utilize the onDelete event handler within the chip component using Material UI in the code snippet below. Upon clicking on the chip, it triggers the Select behavior which opens a dropdown menu. Is there a way to modif ...

Setting the "status" of a queue: A step-by-step guide

I created a function to add a job to the queue with the following code: async addJob(someParameters: SomeParameters): Promise<void> { await this.saveToDb(someParameters); try { await this.jobQueue.add('job', ...

I'm encountering an issue with the preflight request failing the access control check. It seems to be related to not having an HTTP ok status, and I've double-checked everything to make sure I imported

I've encountered an error message stating, "Response to preflight request doesn't pass access control check: It does not have HTTP ok status." Any suggestions on what might be causing this issue? Here is the backend code snippet: app.js app.del ...

Looking for a JavaScript (Angular) event listener to trigger when closing pages and tabs

I am looking for an event that will only work when closing a page or tab, but should not be triggered when the page is refreshed. I am aware of the "beforeunload" event, but it also gets activated on page refresh. Below is the code snippet I am currently ...

multiple event listeners combined into a single function

I'm looking to streamline my button handling in JavaScript by creating just one function that can handle all the buttons on my page. Each button will trigger a different action, so I need a way to differentiate between them. I thought of using one eve ...

Error: The payload in action is not able to be iterated over

Currently, I am delving into the world of ngrx, but I seem to have hit a roadblock. I'm encountering an issue that I can't seem to fix on my own. If anyone out there has some insight and expertise to offer, please help me out. I keep running into ...

Encountering an unexpected error when attempting to make a REST service call using Angular

Trying to retrieve JSON data from a REST service in my Angular 8 application using a GET call with parameters including link, authorization: basic, username, and password. When testing the call in Postman, it returns the expected data without any issues. H ...

Organizing files in an ExpressJs project with Angular2

What is the conventional file structure for a mix of ExpressJs and Angular2 projects? Here's my current setup: Project | |--bin |--node_modules |--public |--images |--javascripts |--stylesheets |--routes |--views |--app.js |-- ...

Tips for maintaining consistent column width when scrolling down (column juggling) within a table in your Angular application

Take a look at this preview of the app I'm currently developing. https://stackblitz.com/edit/angular-ivy-3mrzkr In order to handle the large amount of data in my real app, I needed to incorporate a third-party scrolling module. After testing out cdk ...

Transfer a file to Laravel using $request->input()

Is there a way to upload my file to FTP when I'm sending the data from Angular using JSON format instead of using $request->file("Fichier1") in Laravel? Here is an example of how the data is sent from Angular to Laravel: https://i.stack. ...

The Angular @Input directive may be prone to receiving inaccurate model data

I am currently working on setting up @Input for my component using a model that resembles the following: interface Car { sail?: never tires: number weight: number } interface Boat { tires?: never sail: boolean weight: number } exp ...

What is the reason for certain packages not being placed in the vendor folder during an Angular 2 installation?

I recently created a basic project in angular 2 using their cli. I noticed that when I use 'node install --save' for a material design project, the files are stored in both node_modules and dist/vendor directories. However, when I installed angul ...

What is the process of organizing information with http in Angular 2?

Currently, I am working through a heroes tutorial and have made progress with the code so far. You can view the code <a href="https://plnkr.co/edit/YHzyzm6ZXt4ESr76mNuB?preview" rel="nofollow noreferrer">here</a>. My next goal is to implement ...

Fixing a wrong path in the problem matcher of vscode while compiling using $tsc-watch: A step-by-step

My project workspace directory can be found at C:\salix\fantasy. The TypeScript configuration file is located at C:\salix\fantasy\tsconfig.json Despite my efforts, I'm struggling to have the problem matcher for my project dir ...

Tips for updating the styles within a class for Angular 6 dynamically

Currently, I am able to update the button design using ng-container. Here is a snippet of the code: <ng-container *ngIf="isDisabled;"> <button class="bot-btn-disabled" (click)="confirm()" [disabled]=this. ...

Explore the refined search capabilities within the ng-select dropdown component in Angular

I am currently utilizing the ng-select library for a list of cities, such as: cities = [ {id: 1, name: 'MA, Boston'}, {id: 2, name: 'FL, Miami'}, {id: 3, name: 'NY, New York', disabled: true}, ...

Segment the progress bar into sections

Struggling with an Angular app, and still new to HTML and CSS, I am attempting to create a unique progress bar. I aim to split each section of the progress bar into two subsections with distinct background colors shown in this image: https://i.sstatic.net/ ...

What is the best way to make sure the embedded object fills the entire height of the container div?

I am currently using angular2/4 along with angular-material (https://material.angular.io/). My challenge lies in trying to embed a PDF within it. The issue I am facing is that the height of the PDF object seems to be small and doesn't fully occupy the ...

What steps should I take to manage an error image that is not found in a directory on my computer?

I am currently working with a list that displays various information, along with an image search function in an img tag that looks for a specific image related to the information. However, some of the information does not have a corresponding image and I w ...

"Time" for creating a date with just the year or the month and year

I am trying to convert a date string from the format "YYYYMMDD" to a different format using moment.js. Here is the code snippet I am using: import moment from 'moment'; getDateStr(date: string, format){ return moment(date, 'YYYYMMDD&a ...