动态创建具有特定值的按钮数量以发挥作用

Posted

技术标签:

【中文标题】动态创建具有特定值的按钮数量以发挥作用【英文标题】:Dynamically create number of buttons with specific value to function 【发布时间】:2018-10-07 18:54:37 【问题描述】:

如何在Type Script Ionic2 应用程序中实现:

例如,如果我有btnNmb: number;,当前值为9,则在home.html 表单上动态创建9 按钮,并将此特定范围9 中的每个数字附加到为@987654328 生成的每个按钮@value=1,对于button2value=2等,在函数fnc(value)中传递这个value并将它分配给this.x变量,点击这个@987654337里面的动态创建的按钮@

【问题讨论】:

【参考方案1】:

您可以使用*ngFor 来实现这一点,但 ngFor 需要一个数组或任何具有可迭代接口的对象,所以您可以这样做:

在您的 TypeScript 文件中:

export class YourClass 
  public x = number;
  public btnNmb: number = 9;
  public btnsArray: Array<number> = []; // You need to initialize it so your template doesn't break

  constructor () 
    // You can call it here or on ionViewDidLoad() lifecycle hook
    // Or if the btnNmb is a dynamic number you can call it again when the value changes
    this.generateNumberArray();
  

  // You need to iterate from 1 to the number given in the btnNmb property
  generateNumberArray = () => 
    for(var i = 1; i <= this.btnNmb; i++)
      this.btnsArray.push(i);
    
  

  // The function that's triggered by button click
  fnc = number => this.x = number;

然后在您的 html 中,您将使用 ngfor 来遍历数组并显示多个按钮

<button ion-button *ngFor="let nmb of btnsArray" (click)="fnc(nmb)">nmb</button>

如果您需要更多信息,请联系NgFor docs。希望这会有所帮助。

【讨论】:

您好,抱歉回复晚了,有用的例子,谢谢

以上是关于动态创建具有特定值的按钮数量以发挥作用的主要内容,如果未能解决你的问题,请参考以下文章