簡體   English   中英

Angular 6 * ngFor遍歷兩個數組

[英]Angular 6 *ngFor loop through an two array

我有兩個數組

 firstArray= [{id: 1, name:'firstValue1'}, {id:2, name:'firstValue2'}]

 secondArray= [{ "num": 1, "fullName": SecondValue1 , id:1}]

我想顯示這樣的數據

firstValue1 -------->> SecondValue1

firstValue2 -------->> 

如何在[(ngModel)]或輸入或選擇框中填充這兩個數組?

謝謝您的時間和回復!

而不是將secondArray維護為Array而是將其轉換為HashMap

firstArray = [
    { id: 1, name:'firstValue1' }, 
    { id: 2, name:'firstValue2' }
];
secondArray = { 
    '1': { "num": 1, "fullName": "SecondValue1", id: 1 },
    '2': { "num": 1, "fullName": "SecondValue2", id: 2 },
}

HTML

<div *ngFor="let item of firstArray">
    <p>{{item.name}} --> {{secondArray[item.id]?.fullName}}</p>
</div>

如果您不想手動將索引添加到secondArray ,請嘗試一下:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  firstArray = [
    { id: 1, name: 'firstValue1' },
    { id: 2, name: 'firstValue2' }
  ];

  secondArray = [
    { "num": 1, "fullName": 'SecondValue1', id: 1 },
    { "num": 2, "fullName": 'SecondValue2', id: 2 }
  ];

  getSecondArrayItem(id) {
    return this.secondArray.find(item => item.id === id);
  }
}

並在模板中:

<div *ngFor="let item of firstArray">
    <p>{{item.name}} --> {{ getSecondArrayItem(item.id)?.fullName }}</p>
</div>

這是供您參考的工作樣本StackBlitz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM