从数值生成选择选项

时间:2017-03-03 05:54:45

标签: angular select typescript

我正在尝试根据变量生成下拉列表。

假设totalqty为5,我需要生成下拉选项1,2,3,4,5。

我用angular1完成了它,但它对我不起作用

   <select>
       <option *ngFor="let i of arr(totalqty).fill(1)">{{i}}</option>
   </select>

1 个答案:

答案 0 :(得分:3)

您不能直接在模板中执行此操作。

请在您的组件中执行此操作,请参阅我的工作演示:https://plnkr.co/edit/6Ma2tkfSKfpzxQmiNQl1?p=preview

有两种方式:

  • 生成数组
  • 使用烟斗
@Pipe({ name: 'createArrayOfValues' })
export class CreateArrayOfValuesPipe implements PipeTranfsform {
  public transform(qty: number): number[] {
    if (!qty || isNaN(qty)) return [];
    return new Array(qty).fill(0).map((v, i) => i + 1);
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
    <select>
      <option *ngFor="let i of values">{{i}}</option>
    </select>
    <select>
      <option *ngFor="let i of zerovalues; let idx = index;">{{idx + 1}}</option>
    </select>
    <select>
      <option *ngFor="let i of 5 | createArrayOfValues">{{i}}</option>
    </select>
  `,
})
export class App {
  name:string;
  values = [];
  zerovalues = [];

  constructor() {
    this.name = 'Angular2'
    this.updateValues(5);
  }

  updateValues(qty: number) {
    this.values = new Array(qty).fill(0).map((v, i) => i + 1);
    this.zerovalues = new Array(qty).fill(0);
  }
}
相关问题