问题
I need some help understanding how to use the HTML datalist
with Angular. I have an object here. I would like the dropdown to display the make and model
of the cars. But when you select a car
, the selectedCar
variable should be the entire car object. But the input
should still only show the make and model
.
cars = [{
make: 'Ford',
model: 'GTX',
color: 'green'
}, {
make: 'Ferarri',
model: 'Enzo',
color: 'red'
}, {
make: 'VW',
model: 'Amarok',
color: 'white'
}]
...
<input list="id-car" [(ngModel)]="selectedCar">
<datalist id="id-car">
<option *ngFor="let car of cars" [value]="car">{{car.make}} - {{car.model}}</option>
</datalist>
Here is a place to play with this: https://stackblitz.com/edit/angular-cwmwke
回答1:
Using datalist with not get you what you wish in this case.. here is the code that partially works. After selecting any element the dropdown will not show as it was showing before.
try using select with option. This link can help you more DataList in Angular
html file
<input list="id-car" [(ngModel)]="selectedCar"
value="{{selectedCarObj.model}} - {{selectedCarObj.make}}"
(ngModelChange)="onChange()">
<datalist id="id-car">
<option *ngFor="let car of cars" [value]="car.make">{{car.make}} - {{car.model}}</option>
</datalist>
{{selectedCarObj.model}} - {{selectedCarObj.make}}
typescript file
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
cars = [{
make: 'Ford',
model: 'GTX',
color: 'green'
}, {
make: 'Ferarri',
model: 'Enzo',
color: 'red'
}, {
make: 'VW',
model: 'Amarok',
color: 'white'
}];
selectedCar = "";
selectedCarObj = {};
onChange = () => {
this.selectedCarObj = this.cars.find((c)=> c .make==this.selectedCar);
console.log(this.selectedCarObj)
}
}
来源:https://stackoverflow.com/questions/53058565/angular-and-datalist