角度和数据列表

时间:2018-10-30 06:30:40

标签: html angular datalist

我需要一些帮助,以了解如何在Angular中使用HTML datalist。我在这里有一个对象。我希望下拉菜单显示make and model的汽车。但是,当您选择car时,selectedCar变量应该是整个汽车对象。但是input仍应仅显示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

1 个答案:

答案 0 :(得分:1)

在这种情况下,使用datalist不能获得您想要的结果。这是部分起作用的代码。选择任何元素后,下拉列表将不会像以前一样显示。

尝试使用带有选项的选择。此链接可以帮助您更多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)
  }
}
相关问题