HTML数据列表在角度的怪异行为

问题描述 投票:0回答:1

我已经实现了以下简单组件,以显示具有添加新条目的功能的数据列表。

<h6 *ngIf="withHeader"><label for="select">
  {{title}}
</label></h6>
<label *ngIf="!withHeader" [ngClass]="{'required': required}" for="select">
  {{title}}
</label>
<input id="select" list="dataList" (change)="dataChanged()" [(ngModel)]="selectedValue"/>
<datalist id="dataList">
  <option value=null *ngIf="withButton">{{buttonTitle}}</option>
  <option  *ngFor="let item of data" [ngValue]="item">{{item[shownProperty] || item}}</option>
</datalist>

如果我在另一个组件中使用此组件的一个实例,则效果很好。如果我有一个包含两个dataList-Components的表单,则两个Components都将填充相同的数据。

例如,如果我有一个包含汽车的列表A和一个包含飞机的列表B,则两个列表都将填充汽车-至少在用户打开下拉列表的情况下。

如果我跟踪DOM列表中的数据列表,则A将会填充汽车,B会填充飞机-应该正确。

输入中是否有与列表标识符混淆的内容,该标识符指向首先填充的列表?但是,如果那样的话,我该如何解决呢?输入的列表属性不允许像这样[list]那样调用,因此我可以使用唯一的标识符。

更新:

以下内容不起作用,因为如果使用[list],则会发生以下错误。

Property list is not provided by any applicable directives nor by input element

HTML:

<input id="select" [list]="dataListId" (change)="dataChanged()" [(ngModel)]="selectedValue"/>
<datalist [id]="dataListId">
  <option  *ngFor="let item of data" [ngValue]="item">{{item[shownProperty] || item}}</option>
</datalist>

Component.ts

import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';

@Component({
  selector: 'data-list',
  templateUrl: './data-list.component.html',
  styleUrls: ['./data-list.component.scss']
})
export class DataListComponent {
  @Input() data: any[];
  @Output() selectionChanged = new EventEmitter();
  @Input() selectedValue: any;
  @Input() dataListId: string;

  dataChanged() {
    // Change-Logic
  }

}
javascript html angular dom html-datalist
1个回答
0
投票

您不能在HTML中多次显示相同的ID。在这种情况下,将选择第一个。创建组件实例后,尝试生成ID。您可以在组件上注册一个提供程序工厂,然后为每个创建的实例调用该工厂。然后只需在您的组件中插入id。

const UNIQ_ID_TOKEN = new InjectionToken('ID');
let id = 0;
@Component({
  providers: [
    {
      provide: UNIQ_ID_TOKEN,
      useFactory: () => id++;
    }
  ]
})
class SelectComponent { 
  constructor(
    @Inject(UNIQ_ID_TOKEN)
    public uniqId: number
  ) {}
}

并在模板中使用注入的uniqId。您可以提出更好的id生成。

<h6 *ngIf="withHeader"><label for="{{'select-'uniqId}}">
  {{title}}
</label></h6>
<label *ngIf="!withHeader" [ngClass]="{'required': required}" for="select">
  {{title}}
</label>
<input id="{{'select-'uniqId}}" list="{{'dataList-'uniqId}}" (change)="dataChanged()" [(ngModel)]="selectedValue"/>
<datalist id="{{'dataList-'uniqId}}">
  <option value=null *ngIf="withButton">{{buttonTitle}}</option>
  <option  *ngFor="let item of data" [ngValue]="item">{{item[shownProperty] || item}}</option>
</datalist>
© www.soinside.com 2019 - 2024. All rights reserved.