1
votes

In my angular reactive form i am trying to use three state toggle switch for which i have tried three state switch separately in the link

Three state toggle stackblitz: https://stackblitz.com/edit/angular-6-template-driven-form-validation-gh1dj1

And i need to implement the same with same css inside reactive form on each row inside formarray.

For which i have tried the same html and css and given as formcontrolname like,

      <div class="switch-toggle switch-3 switch-candy">
<ng-container #buttonIcon *ngFor="let option of options" >
  <input type="radio" formControlName="state" [checked]="value === option"
               [value]="option" />
        <label (click)="onSelectionChange(option)"  for="{{option}}">{{option.id}}
        </label></ng-container> <a></a>
          </div> 

But i couldn't achieve the result.

Reactive form stackblitz: https://stackblitz.com/edit/disable-group-control-value-on-another-control-value-for-yqraay

Please click over the add button in the second stackblitz to see the result.. Added the css in app.component.css..

Kindly help me to implement the three state toggle switch as like in the first stackblitz into the reactive form in second stackblitz and need to get the values of selected toggle..

3
I'm already looking into it. Your three-way switch doesn't seem to work in the Reactive Forms.SiddAjmera
Yes you are correct its not working inside reactive form.. Kindly help me in it please to include the three state switch inside reactive form..Maniraj Murugan

3 Answers

3
votes

Just add an [id] to the input tag and an [attr.for] to the label tag. Something like this:

<div 
  class="switch-toggle switch-3 switch-candy">
  <ng-container 
    #buttonIcon 
    *ngFor="let option of options">
    <input 
      type="radio" 
      formControlName="state" 
      [value]="option" 
      [id]="i+option" />
    <label 
      [attr.for]="i+option">
      {{option}}
    </label>
  </ng-container>
  <a></a>
</div>

Here's a Working Sample StackBlitz for your ref.


Thanks to A.Winnen for his comments on the performance implications of using the previous approach.

1
votes

The options array in your reactive component is different than the 3 way switch you implemented. The one in the real component does not have the id.

[
  "on",
  "na",
  "off"
]

You can still use that like this:

<ng-container #buttonIcon *ngFor="let option of options" >
  <input type="radio" formControlName="state" [checked]="value === option"
               [value]="option" />
        <label (click)="onSelectionChange(option)"  for="{{option}}"> 
            {{option}} //**refer the object as the id filed is missing**
        </label>

Second difference is, you are missing the onSelectionChange function in your reactive component