角度和数据列表 [英] Angular and datalist
问题描述
我需要一些帮助,以了解如何在Angular中使用HTML datalist
.我在这里有一个对象.我希望下拉菜单显示汽车的 make and model
.但是,当您选择 car
时, selectedCar
变量应该是整个car对象.但是 input
仍应仅显示 make和model
.
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>
在这里可以玩这个游戏: https://stackblitz.com/edit/angular-cwmwke
Here is a place to play with this: https://stackblitz.com/edit/angular-cwmwke
推荐答案
在这种情况下,使用datalist不能获得所需的结果.这是部分起作用的代码.选择任何元素后,下拉列表将不会像以前一样显示.
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.
尝试使用带有选项的选择.此链接可以帮助您更多 Angular中的数据列表
try using select with option. This link can help you more DataList in Angular
html文件
<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}}
打字稿文件
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)
}
}
这篇关于角度和数据列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!