代码之家  ›  专栏  ›  技术社区  ›  user8667024

动态创建具有特定功能值的按钮数

  •  0
  • user8667024  · 技术社区  · 6 年前

    如何在 Type Script Ionic2 应用程序:

    如果我有 btnNmb: number; 例如,使用当前值 9 ,然后动态创建 9 按钮打开 home.html 表单,并附加此特定范围中的每个数字 9 到每个生成的按钮 button1 value =1 对于 button2 价值 =2 等等,来通过这个 价值 在功能中 fnc(value) 并将其分配给 this.x 变量,其中包含click from dynamicly created按钮 fnc(value) { this.x = value; }

    1 回复  |  直到 6 年前
        1
  •  0
  •   Gabriel Barreto    6 年前

    您可以使用 *ngFor 要实现这一点,ngFor需要一个数组或任何具有iterable接口的对象,因此您可以做以下操作:

    在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;
    }
    

    然后在yout html中使用 ngfor 通过数组调用并显示多个按钮

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

    这是 NgFor docs 如果您需要更多信息。希望这有帮助。