2

I'm building a *ngFor dynamic radio button. I need to add some kind of attribute that can be used to determine if the button is active or not. This is not for the purpose of functionality, the selection builds the property on my reactive form fine. The purpose is to satisfy testing.

   <label *ngFor="let order of orders">
    <input formControlName="orders" type="radio" name="orders" [value]="order.id" />
    {{order.name}}
  </label>

I've tried adding a checked attribute but this just adds the attribute to all radios. I thought angular provided a ngChecked property, but I think that was for AngularJS.

Any solution to determine/show that the selected radio is active would be a solution.

https://stackblitz.com/edit/angular-t2gd4g

2
  • you can add class or get the value by that you will know the selected one Commented Dec 12, 2019 at 10:16
  • or if it just to trigger some style , class are the good case here (ngClass) Commented Dec 12, 2019 at 10:31

2 Answers 2

2

simply by get the value of the form control orders you will be applied to know the selected one or in case of apply a spesifect design you can add a checked class for the selected one

  <label *ngFor="let order of orders"  
           [ngClass]="{'checked':form.get('orders').value == order.id}">
    <input formControlName="orders" type="radio" name="orders" [value]="order.id"  />
    {{order.name}}
  </label>

another way to get the selected order by create a property

  get selectedOrder() { 
    const selected =this.form.get('orders').value;
    if (selected) { 
      return this.orders.find(o => o.id == selected )
    } else {
      return null
    }
  }

demo 🚀

Sign up to request clarification or add additional context in comments.

Comments

2

In your .ts file declare changeHandler() function like this :

  changeHandler(index){
     console.log(`radio-button ${index+1} is active`);
  }

In your .html file, in your *ngFor declare index which can be used to find the current state of checkbox. So the following demo shows which checkbox is active :

    <label *ngFor="let order of orders; let i = index;">
       <input formControlName="orders" type="radio" name="orders" [value]="order.id"  (ngModelChange)="changeHandler(i)"/>
       {{order.name}}
    </label>

Demo : enter link description here

Note : see console to see active button

1 Comment

is there a way to send that back to the input as an attribute rather than in the console?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.