所有动态创建的按钮对同一点击做出反应

时间:2017-12-20 16:32:56

标签: javascript html angular typescript ionic-framework

我使用ngFor创建我的按钮来迭代我的名字数组。我想将我的按钮(例如button1)传递给我在typescript中的函数来改变被点击对象的颜色。但是,我正在努力解决这个问题并感谢任何帮助。

   <ion-list *ngFor="let name of names; let i = index; ">
        <ion-card>
        <div>
          <div>
              <button #button1 ion-button block class="studentbutton {{ studentbutton1 }}" style="background-color:#058D65" (click)="studentbuttonOneClicked(i, button1);"></button>
              <button class="studentbutton  {{ studentbutton2 }}" style="background-color:#7ED321" (click)="studentbuttonTwoClicked(i)"></button>
              <button class="studentbutton {{ studentbutton3 }}" style="background-color:#FFCD56" (click)="studentbuttonThreeClicked(i)"></button>
              <button class="studentbutton {{ studentbutton4 }}" style="background-color:#FF6384" (click)="studentbuttonFourClicked(i)"></button>
              <ion-input placeholder = "contr." id="contribution"></ion-input>
          </div>
        </div>
            </ion-card>
      </ion-list>

这是我的打字稿文件中的功能

studentbuttonOneClicked(i, button1) : void {
    console.log("start"); 
    var eld = document.querySelector('button1'); 
    console.log(eld);
    console.log(button1); 
    let el: HTMLElement = button1; 
    var myEl = angular.element( document.querySelector( button1 ) );
    myEl.addClass('highlighted');
  }

我想专门更改传递的对象,因为否则会修改该行的所有按钮的颜色。

1 个答案:

答案 0 :(得分:0)

如果您只是想突出显示它,那么您可以更改CSS类:

在组件中声明一个变量 isStudentSelected ,其值为-1。

<button *ngFor="let student of students; let i = index" (click)="setSelectedRow(i)" [class.studentHighlighted]="i == isStudentSelected"></button>

使用类名

在CSS中添加突出显示的代码
  //CSS code
 .studentHighlighted{

 background-color:#058D65

}

//Angular Component Code
public isStudentSelected(selectedIndex:int){
  this.selectedStudent = selectedIndex;
}
相关问题