Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 573
Dev Developer Avatar asked Feb 17 '26 01:02

Dev Developer


1 Answers

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.

like image 147
Mahbub Moon Avatar answered Feb 19 '26 15:02

Mahbub Moon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!