PRUDHVI RAJ
PRUDHVI RAJ

Reputation: 41

How to linkup two arrays in Html angular5

I have two arrays like one is City and another is Zipcode

cities=[{name:"aaa"},{name:"bbb"},{name:"ccc"},{name:"ddd"}]
  zipcode=[{num:"111"},{num:"222"},{num:"333"},{num:"444"}]

How to link up two arrays. If i use two forloops, then cities and zipcode becomes twice. Can anyone please help I am expecting output like this aaa-111 bbb-222 ccc-333 ddd-444

But i am not getting expected result. I tried this. linkup array of data stackblitz

Upvotes: 0

Views: 58

Answers (2)

Nandita Sharma
Nandita Sharma

Reputation: 13407

Change your html like this

<li *ngFor="let x of cities;let i=index">
     <div class="form-group" (click)="City(x)">
        <label>{{x.name}}-{{zipcode[i].num}}</label>
     </div>              
</li>

Use the index of the cities array to target the corresponding zipcode array's element. But for this to work you need to ensure that the 2 arrays are of same length and have same index refering to same values in both of the arrays

See updated stackblitz

OR

You can combine the 2 arrays in ngOnInit method using map like shown below.

ngOnInit () {        
    this.cities.map((x:any, i) => x.num = this.zipcode[i].num);
  }

Then use in html like

<div class="form-group" (click)="City(x)">
  <label>{{x.name}}-{{x.num}}</label>
</div>  

Upvotes: 2

SiddAjmera
SiddAjmera

Reputation: 39462

Since you already have the index, why not simply use zipcode[i].num

Something like this:

<div class="admin-page">
  <div class="row">
    <div class="col-md-12">
      <div class="row">
        <div class="co col-md-12">
          <li *ngFor="let x of cities;let i=index">
            <div class="form-group" (click)="City(x)">
              <label>{{x.name}}-{{zipcode[i].num}}</label>
            </div>
          </li>
        </div>
      </div>
    </div>
  </div>
</div>

Here's an Updated Working Sample StackBlitz for your ref.

Upvotes: 0

Related Questions