Search code examples
bootstrap-4toggleangular-ui-bootstraptogglebuttonangular-bootstrap-toggle

How to use bootstrap toggle buttons in angular application for on and off


I want to use the bootstrap toggle buttons(switch buttons) in angular.(The components has to come dynamically from the backend ).

I have tried but toggling the switches is not working properly.

.component.html

<div *ngFor ="let sensor of sensors;let i =index"  (ngModelChange)="dataChanged(selectsensor)" >
<div class="custom-control custom-switch">
  
    <input type="checkbox" class="custom-control-input" (click)="dataChanged(sensor,i)" id="customSwitches">
    <label class="custom-control-label" for="customSwitches">
    {{sensor.name}}  </label>

</div>
</div>


Solution

  • Can you tell us what you are trying to do in the function call dataChanged() And you are calling the same function with different parameter.

    From this structure

    <input type="checkbox" 
    class="custom-control-input" 
    (click)="dataChanged(sensor,i)" id="customSwitches">
    <label class="custom-control-label" for="customSwitches">
    {{sensor.name}}  </label>
    

    to

    <input
      type="checkbox"
      class="custom-control-input"
      id="customSwitches{{i}}"
    />
    <label class="custom-control-label" for="customSwitches{{i}}">
    {{sensor.name}}  </label>
    

    The id of the element is duplicated n number(n - number of sensors) of times in your structure. As per standard we can't duplicate the same id. So please index of the sensor to it. now it's working for me.

    Note: we don't know what is the implementation inside the function dataChanged(). That also might cause issue. We removed both the function call from both places.