在 Angular 2+ 中可以做到这一点吗?
假设我有以下对象:
myParent = [{id: 1, code: 'code1', title: 'parentTitle1'}, {id: 2, code: 'code2', title: 'parentTitle2'}];
myChild = {code1: [{id: 1, title: 'childTitle1'}, {id: 2, title: 'childTitle2'}], code2: [{id: 4, title: 'childTitle1'}]
我想迭代第一个,然后使用父对象的“code”值作为索引显示第二个项目:
<h3 *ngFor="let parent of myParent">{{parent .title}}
<br>
<span *ngFor="let child of myChild[parent.code]"> {{child.title}} </span>
<br>
</h3>
我在控制台上没有收到任何错误,但子项“for”没有显示任何内容。我曾经在 AngularJS 上这样做过,但不确定是否可以在 NG7 中这样做
最佳答案
检查这个stackblitz 。这不适合你吗?
我尝试使用这些数据:
myParent = [{id: 1, code: 'code1', title: 'parentTitle1'}, {id: 2, code: 'code2', title: 'parentTitle2'}];
myChild = {code1: [{id: 1, title: 'childTitle1'}, {id: 2, title: 'childTitle2'}], code2: [{id: 4, title: 'childTitle1'}]};
和 html
<h3 *ngFor="let parent of myParent">{{parent .title}}
<br>
<span *ngFor="let child of myChild[parent.code]"> {{child.title}} </span>
<br>
</h3>
stackblitz 正在按您的预期运行。您能否分享更多代码,因为数据似乎可能不匹配。
关于javascript - Angular 7 嵌套使用父值作为子值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58882195/