Angular:使用单个变量进行多个按钮操作

时间:2018-03-26 10:46:54

标签: javascript html angular

我想将单个varible用于多个按钮,以便单独启用和禁用。

http://win-lfl4bgulf29/_api/lists/getbytitle('EvertList')/views

如何根据选择单独启用或禁用上述按钮?我只是试图禁用所有这些或启用所有这些。

3 个答案:

答案 0 :(得分:2)

您可以跟踪按钮的跟踪状态:



<button class="button" [disabled]="buttonStates['button1']" (click)="onToggle('button1')"> button 1</button>
<button class="button" [disabled]="buttonStates['button2']" (click)="onToggle('button2')"> button 2</button>
<button class="button" [disabled]="buttonStates['button3']" (click)="onToggle('button3')"> button 3</button>
<button class="button" [disabled]="buttonStates['button4']" (click)="onToggle('button4')"> button 4</button>


export class YourComponent {
  buttonStates: any = {
    button1: true,
    button2: false,
    button3: false,
    button4: true
  };
  onToggle(button) {
    this.buttonStates[button] = !this.buttonStates[button];
  }
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用数组,因为它在技术上是单个变量

<强> HTML

turtles with [ member? self cheaters = false ]

<强> app.component.ts

<button class="button" [disabled]="btnState[0]" (click)="foo('val1')"> button 1</button>
<button class="button" [disabled]="btnState[1]" (click)="foo('val2')"> button 2</button>
<button class="button" [disabled]="btnState[2]" (click)="foo('val3')"> button 3</button>
<button class="button" [disabled]="btnState[3]" (click)="foo('val4')"> button 4</button>

Stackblitz

或者,您甚至可以使用对象

<强> HTML

btnState = [false, false, true, true];

<强> app.component.ts

<button class="button" [disabled]="btnState.btn1" (click)="foo('val1')"> button 1</button>
<button class="button" [disabled]="btnState.btn2" (click)="foo('val2')"> button 2</button>
<button class="button" [disabled]="btnState.btn3" (click)="foo('val3')"> button 3</button>
<button class="button" [disabled]="btnState.btn4" (click)="foo('val4')"> button 4</button>

Stackblitz

答案 2 :(得分:0)

为什么要一个变量?如果你这样做,我会使用地图。

<button class="button" [disabled]="btnState['val1']" (click)="btnClickFunction('val1')"> button 1</button>
<button class="button" [disabled]="btnState['val2']" (click)="btnClickFunction('val2')"> button 2</button>
<button class="button" [disabled]="btnState['val3']" (click)="btnClickFunction('val3')"> button 3</button>
<button class="button" [disabled]="btnState['val4']" (click)="btnClickFunction('val4')"> button 4</button>

并在你的clickFunction中:

btnClickFunction(val){
   if(!this.btnState.hasOwnProperty(val)){
      this.btnState[val] = false;
   }
   this.btnState[val] = !this.btnState[val];
}