Skip to content
Advertisement

Change dynamically css proprety of various inputs in angular

I would like to know the correct way to do one thing. I have those buttons, and I want the opacity of a button to increase when pressed. I’ve done lik this, but I’m afraid it’s not a good solution… I always hear that use jQuery in angular is not a good thing, so I try to not use the .css proprety of jquery of an element…

<div class="calibrationDiv" *ngIf="startCalibration" (click)="onClick($event)" >

    
    <input type="button" class="Calibration" id="Pt1" [style.opacity]="0.2*calibrationPoints['Pt1'] + 0.2">
    <input type="button" class="Calibration" id="Pt2" [style.opacity]="0.2*calibrationPoints['Pt2'] + 0.2">
    <input type="button" class="Calibration" id="Pt3" [style.opacity]="0.2*calibrationPoints['Pt3'] + 0.2">
    <input type="button" class="Calibration" id="Pt4" [style.opacity]="0.2*calibrationPoints['Pt4'] + 0.2">
    <input type="button" class="Calibration" id="Pt5" [style.opacity]="0.2*calibrationPoints['Pt5'] + 0.2">
    <input type="button" class="Calibration" id="Pt6" [style.opacity]="0.2*calibrationPoints['Pt6'] + 0.2">
    <input type="button" class="Calibration" id="Pt7" [style.opacity]="0.2*calibrationPoints['Pt7'] + 0.2">
    <input type="button" class="Calibration" id="Pt8" [style.opacity]="0.2*calibrationPoints['Pt8'] + 0.2">
    <input type="button" class="Calibration" id="Pt9" [style.opacity]="0.2*calibrationPoints['Pt9'] + 0.2">
    
</div>

Advertisement

Answer

I made like that :

  <input *ngFor = "let calibrationPoint of calibrationPoints; let i = index"
            type = "button"
            class = "Calibration"
            (click) = "onClick(i)"
            [style.opacity] = "calibrationPoint['opacity']">

And in the .ts file:

export class CalibrationComponent  {


  private calibrationPoints: Array<Object>;                           // CSS proprety of Calibration points     


  constructor() {
    // Initialize the array of CSS propreties
    this.calibrationPoints = new Array(9);
    for (var i = 0; i < 9; i++) {
      this.calibrationPoints[i] = {opacity: 0.2}
    }
   }

 
  /**
   * Modify the css propreties of a calibration point on click.
   * @param {number} index The index of the point to modify.
   */
  private onClick(index: number): void { 
    if (this.calibrationPoints[index]["opacity"] < 1)
      this.calibrationPoints[index]["opacity"] += 0.2
  }
}

Not sure if it’s the best method but it works.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement