Dev Developer
Dev Developer

Reputation: 113

finding within array of object angular 6/typescript/javascript

I am having below code in my HTML template of my angular 6 application.

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

basically I am trying to search within object of participants array by updatedBy value anad see its matching object has firstName property not null or not but it gives me error that firstName is not defined.

I also tried placing question mark after ] brackets like below but did not yield any result.

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

Below is 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"
}

Please let me know if anything you know about this.

Thanks

Upvotes: 3

Views: 287

Answers (2)

info2ankit
info2ankit

Reputation: 303

this.conversation.participants.find(x => x.userId.toLowerCase() === this.conversation.updatedBy).firstName;

stackblitz

Upvotes: 0

Mahbub Moon
Mahbub Moon

Reputation: 501

You need to declare a variable in your component.ts file which will store the boolean result that you are using in *ngIf. And also update the value when the conversation variable changes.

For example, in component.ts

let firstNameExists = false;

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

and then in your component.html

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

Note: the expression is being used in ts because it's a very bad practice to use expressions in angular bindings.

Upvotes: 1

Related Questions