简体   繁体   English

如何在Angular中使用ngFor获取嵌套对象数组的选定值?

[英]How to get selected value of nested object array using ngFor in Angular?

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:我的 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

If I understand correctly, you can pass the iteration object to the TS as a function parameter.如果我理解正确,您可以将迭代对象作为函数参数传递给 TS。 Example:例子:

In your HTML you should:在您的 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(obj, item)">Click</button>
  </div>
</div>

In the TS you do在 TS 你做

getDetails(obj, item) {
  console.log(obj.time, item.name); // The values you want here.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM