动态创建具有特定功能的按钮数量
Dynamically create number of buttons with specific value to function
如何在 Type Script
Ionic2
应用程序中实现:
例如,如果我有 btnNmb: number;
,当前值为 9
,则在 home.html
表单上动态创建 9
按钮,并附上该特定范围内的每个数字9
到 button1
value
=1
、button2
value
=2
等的每个生成的按钮,以传递此 value
在函数 fnc(value)
中,并通过单击此 fnc(value) { this.x = value; }
中动态创建的按钮将其分配给 this.x
变量
您可以使用 *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。希望这有帮助。
如何在 Type Script
Ionic2
应用程序中实现:
例如,如果我有 btnNmb: number;
,当前值为 9
,则在 home.html
表单上动态创建 9
按钮,并附上该特定范围内的每个数字9
到 button1
value
=1
、button2
value
=2
等的每个生成的按钮,以传递此 value
在函数 fnc(value)
中,并通过单击此 fnc(value) { this.x = value; }
this.x
变量
您可以使用 *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。希望这有帮助。