2017-05-09 38 views
2

使用Angular2使用循環將下拉列表數值與從1到100的數字綁定的最佳方式是什麼?Angular2:使用'n'數字綁定下拉列表

對於有限數量的值,我正在使用Ngprime下拉列表,但是如何爲'n'個數值實現此目的?

模板:

<p-dropdown [options]="tests" [(ngModel)]="selectedCar" [style]="{'width':'150px'}" editable="editable" placeholder="Select a Brand"></p-dropdown> 

組件:

this.tests = []; 
this.test.push({label: 'Audi', value: 'Audi'}); 

任何人都可以指導我?

回答

2

與角2 1選項100的下拉會是這樣的:

在組件:

export class DropDownClass { 
    constructor() { 
    this.numbers = new Array(100).fill().map((x,i)=>i); // [0,1,2,3,4,...,100] 
    } 
} 

模板:

<select name="my-dropdown" [(ngModel)]="myDropdownModel"> 
    <option *ngFor="let number of numbers" [ngValue]="number">{{number}}</option> 
</select> 
+0

謝謝你的迴應,我得到一個錯誤「提供的參數不匹配,通話對象的任何簽名。」(法)陣列 .fill(value:any,start ?: number,end ?: number):any [] ...我應該指定開始和結束值嗎? – AnnMary

+0

@安妮瑪瑞沒問題。但它爲你工作?它解決了你的問題嗎?你有沒有遇到任何困難?祝你今天愉快! :D – SrAxi

+0

error_handler.js:54 EXCEPTION:未捕獲(承諾):TypeError:無法讀取未定義的屬性「填充」 TypeError:無法讀取未定義的屬性「填充」 – AnnMary

0

工作守則

輸入模板:

<label for="percentage">Percentage</label> 
    <p-dropdown formControlName="PercentageAbsence" [options]="numbers" [style]="{'width':'200px'}"> 
    </p-dropdown> 

在組分:

import { SelectItem } from 'primeng/primeng'; 
    export class Test{ 
    numbers: SelectItem[] = []; 
    constructor(){ 
     Array(100).fill(0).map((x, i) => { 
     this.numbers.push({ label: `${i + 1}`, value: i + 1 }) 
    }); 
    } 
} 
0

在組分:(YourComponent.ts)

export class YourComponent { 
itemQuantity = []; // instantiates the object to hold array of numbers 

public ngOnInit() { 
    this.itemQuantity = Array(5).fill(0).map((x,i)=>i+1); // fills array with 5 incremental entries starting from 1 (hence the "i+1"). To start at zero remove the "+1" 
} 

}

在模板:(YourComponent.html)

<option *ngFor="let number of itemQuantity" value="{{number}}">{{number}}</option> 

結果是具有五個條目的下拉列表編號爲1至5

「值=」 {{數}}」是可選的,如果要用於每個選擇項目不同的文本和值,例如得到1號可以使用數{{數}}