Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataList in Angular

I have a <datalist> and <select> as follows:

Updated:

Example 1:

<input type="text"  list="codes" [(ngModel)]="codeValue" (change)="saveCode(codeValue)">
<datalist id="codes">
  <option *ngFor="let c of codeList" [value]="c.code" >{{c.name}}</option>
</datalist>

<select type="text"  list="codes" [(ngModel)]="codeValue1" (change)="saveCode(codeValue)">
  <option *ngFor="let c of codeList" [value]="c.code" >{{c.name}}</option>
</select>

codeList Array in component.ts

    codeList = [
    { code: 'abcdhe568dhjkldn', name: 'item1' },
    { code: 'ksdkcs7238t8cds', name: 'item2' },
    { code: 'kascggibebbi', name: 'item3' }
  ];

DataList is showing both name (c.name) and value (c.code) in the options and storing whatever is present in value whereas select is showing name (c.name) and storing value(c.code).

Behavior of datalist

Behavior of <dataList>

Behavior of select

Behavior of <select>

Example 2:

<datalist id="codes">
<option *ngFor = "let i of [1,2,3,4]" [value]="i">{{i-1}}</option>
</datalist>

{{a}}

I want to show the value of i-1 in the suggestion box but bind the variable 'a' with i.

Existing Solution in HTML

From this post Show datalist labels but submit the actual value I see that we can use "data-value" to acheive the functionality in HTML. How can I achieve the same functionality in Angular.

Please help!

Thanks in advance.

like image 928
Sai Raman Kilambi Avatar asked Oct 17 '22 20:10

Sai Raman Kilambi


1 Answers

Try Like this....

html File

<input type="text"  list="codes" [(ngModel)]="codeValue" (change)="saveCode($event)">
<datalist id="codes">
<option *ngFor="let c of codeList" [value]="c.name" >{{c.name}}</option>
</datalist>

ts File

 codeList = [
{ code: 'abcdhe568dhjkldn', name: 'item1' },
{ code: 'ksdkcs7238t8cds', name: 'item2' },
{ code: 'kascggibebbi', name: 'item3' }
];

 public saveCode(e): void {
let name = e.target.value;
let list = this.codeList.filter(x => x.name === name)[0];
console.log(list.id);
}
like image 103
Nithin mm Avatar answered Oct 20 '22 23:10

Nithin mm