我有以下变量:
var1 = null;
var2 = null;
var3 = null;
var4 = null;
var5 = null;
和以下按钮:
<button>btn1</button>
<button>btn2</button>
<button>btn3</button>
<button>btn4</button>
<button>btn5</button>
<button>btnNull</button>
我想要做的是通过单击btn1将var1设置为true,将所有其他设置为false,与其他4个按钮的行为相同,并通过单击btnNull将所有变量设置为null。
我所做的是以下内容:
btn1(){
this.var1=true;
this.var2=this.var3=this.var4=this.var5=false;
}
btn2(){
this.var2=true;
this.var1=this.var3=this.var4=this.var5=false;
}
btn3(){
this.var3=true;
this.var1=this.var2=this.var4=this.var5=false;
}
btn4(){
this.var4=true;
this.var1=this.var2=this.var3=this.var5=false;
}
btn5(){
this.var5=true;
this.var1=this.var2=this.var3=this.var4=false;
}
btnNull(){
this.var1=this.var2=this.var3=this.var4=this.var5=null;
}
并在不同的按钮中使用这五种方法,如下所示:
<button (click)="btn1()">btn1</button>
<button (click)="btn2()">btn2</button>
<button (click)="btn3()">btn3</button>
<button (click)="btn4()">btn4</button>
<button (click)="btn5()">btn5</button>
<button (click)="btnNull()">btnNull</button>
这是很多代码并且看起来不是很好,我怎样才能用一两种方法实现相同的行为?
答案 0 :(得分:2)
您可以创建一个数组..但我不会将var
用作变量名,因为它已被保留。
component.ts
vals = [null, null, null, null, null];
然后在component.html
<button *ngFor="let val of vals; let i =index"
(click)="vals.fill(false); vals[i] = true">btn {{i + 1}}</button>
<button (click)="vals.fill(null);">btnNull</button>
<p *ngFor="let val of vals; let i = index">val{{i}} = {{val}}</p>