Angular and datalist

我的未来我决定 提交于 2021-02-08 15:13:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!