1

I have an object as:

test = [
{"obj1": {"time":"8:00","array":[{name: "user1", "language": "En"},{"name": "user4", "language": "Fr"}]}}
{"obj2": {"time":"8:00","array":[{name: "user2", "language": "Fr"},{"name": "user3", "language": "Sp"}]}}
]

My HTML:

<div *ngFor="let obj of test">
<div *ngFor="let item of obj.array">
<p>{{obj.time}}</p>
<p>{{item.name}}</p>
<button (click)="getDetails()">Click</button>
</div>

When the button is clicked, I need to get the value of the "time" and "name". I know how to get the value of time as it is only one per the object. But, I am not sure how to get the values of the nested array. I think it can be done by using "index" approach. But, I cannot make it work.

Desired Output: When I click on the button:

8:00,
user1,
En
4
  • let item of obj.array is problematic as array is nested within a dynamic property. In one element it is nested in obj1 and in the next it is nested in obj2. You can make it work, but it would be much cleaner if the data model was consistent. Commented Nov 18, 2020 at 23:51
  • Also a little debugging tip. Within your markup, if you put {{ obj | json }} in there, when you run the page, angular will spit out the obj in json, so you can take a look at what you are dealing with. Commented Nov 18, 2020 at 23:55
  • 1
    Do you want to get value of all names? I didn't get the point of the question. Commented Nov 18, 2020 at 23:56
  • @JorgeMussato , When I click on the button, I should get the respective nested array object name and language and the time in the main object. Commented Nov 18, 2020 at 23:57

1 Answer 1

1

If I understand correctly, you can pass the iteration object to the TS as a function parameter. Example:

In your HTML you should:

<div *ngFor="let obj of test">
  <div *ngFor="let item of obj.array">
    <p>{{obj.time}}</p>
    <p>{{item.name}}</p>
    <button (click)="getDetails(obj, item)">Click</button>
  </div>
</div>

In the TS you do

getDetails(obj, item) {
  console.log(obj.time, item.name); // The values you want here.
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.