我正在使用最新版本的Angular JS。
我使用的示例来自(创建选项组):
https://material.angular.io/components/select/examples
在示例中,HTML代码为:
<mat-form-field>
<mat-select placeholder="Pokemon" [formControl]="pokemonControl">
<mat-option>-- None --</mat-option>
<mat-optgroup *ngFor="let group of pokemonGroups" [label]="group.name"
[disabled]="group.disabled">
<mat-option *ngFor="let pokemon of group.pokemon" [value]="pokemon.value">
{{pokemon.viewValue}}
</mat-option>
</mat-optgroup>
</mat-select>
</mat-form-field>
我试图仅在下拉列表中显示数组的第一个元素。我将在页面的不同位置使用此阵列的“宠物小精灵”群组,但我现在只想显示1个群组。
我尝试过:
<mat-optgroup *ngFor="let group of pokemonGroups[0]" [label]="group.name">
为了仅访问第一个元素(草):
pokemonGroups: PokemonGroup[] = [
{
name: 'Grass',
pokemon: [
{value: 'bulbasaur-0', viewValue: 'Bulbasaur'},
{value: 'oddish-1', viewValue: 'Oddish'},
{value: 'bellsprout-2', viewValue: 'Bellsprout'}
]
},
{
name: 'Water',
pokemon: [
{value: 'squirtle-3', viewValue: 'Squirtle'},
{value: 'psyduck-4', viewValue: 'Psyduck'},
{value: 'horsea-5', viewValue: 'Horsea'}
]
},
{
name: 'Fire',
disabled: true,
pokemon: [
{value: 'charmander-6', viewValue: 'Charmander'},
{value: 'vulpix-7', viewValue: 'Vulpix'},
{value: 'flareon-8', viewValue: 'Flareon'}
]
},
{
name: 'Psychic',
pokemon: [
{value: 'mew-9', viewValue: 'Mew'},
{value: 'mewtwo-10', viewValue: 'Mewtwo'},
]
}
];
我得到的错误:
ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'Peru'. NgFor only supports binding to Iterables such as Arrays.
at NgForOf.ngOnChanges
Angular的新手。希望获得帮助/支持
答案 0 :(得分:2)
如果您只想显示一组,您是选择使用*ngFor
吗?
您可以直接使用-
<mat-optgroup [label]="pokemonGroups[0].name">
答案 1 :(得分:1)
您需要通过将对象包装在[]
中来将其变成数组。将您的模板更新为:
<mat-optgroup *ngFor="let group of [pokemonGroups[0]]" [label]="group.name">
答案 2 :(得分:0)
您可以简单地在数组上使用slice
函数来排除除第一个项以外的所有项
<mat-optgroup *ngFor="let group of pokemonGroups.slice(pokemonGroups.length-1)" [label]="group.name">
答案 3 :(得分:0)
您可以在切片数据数组之前检查@Amit Chigadani解决方案。
<div *ngFor="let group of (pokemonGroups? pokemonGroups.slice(0,1): [])" >