Search code examples
arraysangulartypescriptangular8angular14

How to show the object array value in the each dropdown in angular 14


Trying to show object array value in the dropdown. I have one object and it will have 'Car', 'Bus', 'Cycle', 'MotorCycle', 'Train' array value. I want to show the value of this object in each dropdown. Like first dropdown Car array value, second dropdown Bus value, third dropdown Cycle, fourth dropdown MotorCycle value and fifth dropdown Train value. I have used input decorator. So, How to show these value in each dropdown.

main.component.ts:

export class MainComponent implements OnInit {
travals = {
Car: ['Good', 'Bad'],
Bus: ['Supper', 'Coll'],
Cycle: ['Small', 'Big'],
MotorCycle: ['Too Big', 'Scooty'],
Train: ['Special', 'Nomal', 'Super Fast'],
};

vehicle = ['Car', 'Bus', 'Cycle', 'MotorCycle', 'Train']; 
constructor() {} 
ngOnInit() {}
}

vehicle.component.ts:

export class VehicleComponent implements OnInit {
@Input() data: any = []; 
constructor() {} 
ngOnInit() {
console.log(this.data);
}
}

Demo : https://stackblitz.com/edit/angular-ivy-1w4gxt?file=src%2Fapp%2Fshared%2Fvehicle%2Fvehicle.component.ts


Solution

  • Your main.component.html

    1. using keyvalue pipe:
    <div
      class="custom-select"
      style="width:400px;"
      *ngFor="let vehicleType of travals | keyvalue"
    >
      <p>{{ vehicleType.key }}</p>
      <app-vehicle [data]="vehicleType.value"></app-vehicle>
    </div>
    
    1. using hardcoded array of vehicle:
    <div
      class="custom-select"
      style="width:400px;"
      *ngFor="let vehicleType of vehicle"
    >
      <p>{{ vehicleType }}</p>
      <app-vehicle [data]="travals[vehicleType]"></app-vehicle>
    </div>
    

    Your vehicle.component.html:

    <select>
      <option value="{{ val }}" *ngFor="let val of data">
        {{ val }}
      </option>
    </select>
    

    This should work. keyvalue pipe allows to iterate objects and to access key value pairs. You can use them as you like in your particular task.

    Link in documentation https://angular.io/api/common/KeyValuePipe