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/app/shared/vehicle/vehicle.component.ts
CodePudding user response:
Your main.component.html
- using keyvalue pipe:
<div
style="width:400px;"
*ngFor="let vehicleType of travals | keyvalue"
>
<p>{{ vehicleType.key }}</p>
<app-vehicle [data]="vehicleType.value"></app-vehicle>
</div>
- using hardcoded array of vehicle:
<div
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