我有一个这样的列表...
export const inventory=
[
'coffee'
'tea'
'wine'
'beer'
'sake'
....
];
在html中,我正在遍历创建下拉菜单,次数固定。
<div *ngFor="let number of numbers; let i = index" >
<select class="roles-select" [(ngModel)]="number.selectedItem" (change)="selected($event)" >
<option *ngFor="let inv of inventoryList; let x = index" [ngValue]="inv">{{inv}}
</option>
</select>
</div>
在我的组件中,它已经可以工作了。
public numbers = [];
public selectedItem;
public inventoryList = inventory;
constructor() {
this.numbers = Array(3).fill(0).map((x , i) => i);
}
ngOnInit() {
this.selectedItem = Math.floor(Math.random() * 9); // generate random default in the list?
}
selected(value: any) {
console.log('selected dropdown: ' + value.target.name + value.target.value);
}
我想要的是默认为下拉菜单随机生成3个不同的项目。...但我不确定该怎么做。
答案 0 :(得分:2)
尝试一下:
import { Component } from "@angular/core";
export const inventory = ["coffee", "tea", "wine", "beer", "sake"];
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
public numbers = [];
public selectedItems = [];
public inventoryList = inventory;
ngOnInit() {
this.numbers = Array(3).fill(0).map((x, i) => i);
this.numbers.forEach(num => this.selectedItems.push(inventory[Math.floor(Math.random()*inventory.length)]));
}
selected(value: any) {
console.log("selected dropdown: " + value.target.name + value.target.value);
}
}
在您的模板中:
<div *ngFor="let number of numbers; let i = index">
<select class="roles-select" [(ngModel)]="selectedItems[i]" (change)="selected($event)" >
<option *ngFor="let inv of inventoryList; let x = index">{{inv}}</option>
</select>
</div>
这是您推荐的Working Sample StackBlitz。
我建议为此使用反应式表格。
答案 1 :(得分:1)
做这样的事情:
public numbers = [];
inventoryList = ["coffee", "tea", "wine", "beer", "sake"];
constructor() {}
ngOnInit() {
this.numbers = Array(3)
.fill(0)
.map((x, i) => {
return { value: Math.floor(Math.random() * this.inventoryList.length) };
});
}
HTML:
<div *ngFor="let number of numbers; let i = index" >
{{number | json}}
<select class="roles-select" [(ngModel)]="number.value" (change)="selected($event)" >
<option *ngFor="let inv of inventoryList; let x = index" [ngValue]="x">{{inv}}
</option>
</select>
</div>