Locating items within an array of objects using Angular 6 with TypeScript or JavaScript

I have the following code in my HTML template for my Angular 6 application.

<div *ngIf ="conversation.participants[conversation.updatedBy.toLowerCase()].firstName">somedata </div>

My goal is to search within the participants array object based on the updatedBy value and check if the matching object has a non-null firstName property. However, I am getting an error saying that firstName is not defined.

I also tried adding a question mark after the closing square brackets as follows, but it did not give me any result:

conversation.participants[conversation.updatedBy.toLowerCase()]?.firstName

Here is the JSON object:

"participants": [{
        "dateJoin": 1520409578,
        "dateLeft": 0,
        "firstName": "edh",
        "internalId": 165,
        "invitedBy": "edh",
        "lastName": "edh",
        "userId": "edh"
    }, {
        "dateJoin": 1520409578,
        "dateLeft": 0,
        "firstName": "",
        "internalId": 166,
        "invitedBy": "edh",
        "lastName": "",
        "userId": "ATB"
    }],
    "dataInAB": "ATB",
    "subject": "test ",
    "unreadMessageCount": 0,
    "updateDate": 1520585258,
    "updatedBy": "atb"
}

If you have any insights or solutions regarding this issue, please let me know.

Thank you.

Answer №1

To ensure proper functionality in your component.ts file, it is essential to declare a variable that will hold the boolean value used in the *ngIf directive. This variable should also be updated whenever there are changes in the 'conversation' variable.

Here's an example implementation in component.ts:

let nameExists = false;

getConversationData(){
  this.conversation = ....
  this.nameExists  = this.conversation.participants.find(m=>m.userId.toLowerCase()==this.conversation.updatedBy).name? true: false;
}

Subsequently, in your component.html file:

<div *ngIf ="nameExists">somedata </div>

Please bear in mind that utilizing expressions within angular bindings is discouraged due to best practices.

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

Error message: An error occurred while executing the AJAX PHP code due to a TypeError, specifically stating that the property 'status' cannot be

For some reason, I keep receiving an undefined return for my response. The event handler in index.php triggers the following code: $.post("getData.php", onNewPost()); function onNewPost (response){ if (response.status == "OK") { console.log(resp ...

Issues with displaying HTML5 audio player in iOS Chrome and Safari browsers

My html5/jquery/php audio player is working well on desktop browsers, but when I tried testing it on iOS, all I could see was a grey track bar. I suspect that the controls are hidden behind the track bar because sometimes the associated file starts playing ...

Getting form field values with JQuery

I am currently facing an issue with a form field in HTML. Here is the code snippet: <form id="tasklist"> <input type="text" id="name" ...></input> ... additional form elements go here ... </form> Although I am trying to retrie ...

Ways to verify user authentication for navigating Vue routes

Working on a Single Page Application with Vue front-end, Express, and Parse (parse-platform) for back-end. After authenticating the user, I store their info in a session variable req.session.user = result; before sending it back to the client using res.sta ...

Receiving an `Invalid module name in augmentation` error is a common issue when using the DefaultTheme in Material

After following the guidelines outlined in the migration documentation (v4 to v5), I have implemented the changes in my theme: import { createTheme, Theme } from '@mui/material/styles' import { grey } from '@mui/material/colors' declar ...

Emulate an AngularJS ng-click action

My website has HTML code with three buttons: <button ng-click='showStats(player.data,0)'>Death Match</button> <button ng-click='showStats(player.data,1)'>Champions Rumble</button> <button ng-click='sho ...

Using the <script> attribute within the <head> tag without the async or defer attributes

https://i.stack.imgur.com/cRFaR.pngCurious about Reddit's use of the async or defer attribute in the script tag. Are there situations where blocking the parser is necessary? ...

Inject a value sent from response.render directly into the script tag

Below you will find a pug snippet. I am looking for a way to dynamically insert the user value into the chatConfig object. script. var chatConfig = { user : 'foo', pass : 'bar', } When rendering from my Express applicatio ...

Ways to verify if an array contains elements from other arrays in Typescript

How can I verify if the winningConditions are present in chosenNumbers? The chosenNumbers array is of varying lengths and consists of a mix of numbers. For example, one of the winning conditions is [0, 3, 6], but there is also the number 2 included. How ...

Discovering the source DOM element that initiated ng-change

I am currently working with angularJS and have multiple <select> elements on my webpage, each with its own ng-change function. Here is an example: <select id="hairColorComponent" ng-model="hairColor" ng-options="option.name for option in ...

An issue arises in Node.js and MongoDB where data is being returned from the previous update instead of the most

Currently, I'm delving into the world of Node.js and creating a platform where individuals can vote on different items and view the results afterward. The voting process involves utilizing the /coffeeorwater POST route, which then redirects to the /re ...

Error encountered in amCharts Serial Chart when data parsing is enabled with the setting "parseDates": true which resulted in the failure to display data

Using Spring as a webservice, I received a JSON response with stock data: [ { "date": "2016-04-17", "open": 1085.0, "high": 1092.2, "low": 1072.0, "close": 1088.3, "volume": 54100, "value": 1088.3 }, { "date": "2016-04-14", "open": 1081. ...

The function insertAdjacentHTML does not seem to be functioning properly when used with a

I am working with a parent element that contains some child elements. I create a DocumentFragment and clone certain nodes, adding them to the fragment. Then, I attempt to insert the fragment into the DOM using the insertAdjacentHTML method. Here is an ex ...

Vue.js: SCSS @import being overlooked

I've found great success using VueJS in two different projects. As I prepare to launch these projects, I'm encountering an issue when generating the files with npm run build. One project, created recently, is working fine. However, the other pro ...

Attempting to deploy a GitHub repository onto Railway.app has led to an Application Error. It seems like the issue may lie in whether your app is

I encountered an Application Error while deploying my project to railway.app. The error message prompts, "Is your app correctly listening on $PORT?". Initially, my project was a combination of JS and jQuery. However, I later integrated webpack.config.js t ...

Guide to center align fields in Ionic and Angular

I am working on creating a login screen that resembles the image provided. I have managed to set the background image, input fields, and buttons successfully. However, I am encountering a few issues: The width of my input field is taking up the entire spa ...

A Guide to Implementing Schema.virtual in TypeScript

After switching from using schema.virtual in JavaScript to TypeScript, I encountered an error when trying to use it with TypeScript. Below is my code: UserSchema.virtual('fullname').get(function () { return `${this.firstName} ${this.lastName}` ...

List of items displayed in alphabetical order using the ng-repeat directive:-

I'm working with an ng-repeat block in the code snippet below. My goal is to have the placeholder [[THE ALPHABET]] render as a, b, c, d representing bullets for the list in their respective order. There will always be 4 values present. What would be t ...

what is the mechanism behind __dirname in Node.js?

Node.js is a new technology for me and I recently discovered the "__dirname" feature which is really useful for obtaining the absolute path of the script. However, I am intrigued by how it works and how it manages to interpret the directory structure. De ...

Leverage information stored in an array within the HandsonTable Angular directive

Some of my columns in a HandsoneTable created using Angular directives are not rendering when I try to use an array as the data source with common array notation (name[0]). I'm unsure if this is supposed to work like this or if I am doing something wr ...