0

https://stackblitz.com/edit/angular-7aqzj2

places = ['effil tower','new discover']

new FormGroup({place: new FormControl()});
 <div *ngIf="places?.length > 0" class="col-12">
            <div style=" padding-top: 1em; ">
                <label  *ngFor="let place of places">
                    <input  formControlName="place" type="radio">{{place}}
                </label>
            </div>
        </div>

I am trying to add the radio button with the same form-control name and the value is coming through services.

while doing so it has the same form-control name so getting selected both at a same time.

is there any way to differentiate both and select one at a time?

a.p. patel
  • 103
  • 4
  • 25

3 Answers3

3

You need to use property binding for each option:

<input  formControlName="place" type="radio" [value]="place">
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
  • thanks a lot.. it worked.. just curious how I can make the first index of the array by default in the dropdown? – a.p. patel Feb 07 '20 at 17:13
  • 1
    Glad to help! Sorry didn't get you. Which dropdown are you talking about? – Nicholas K Feb 07 '20 at 17:15
  • Extend your *ngFor to pass the first value through `*ngFor="let place of places; let first = first;"`. And then set selected if first is true, `` – Sam Feb 07 '20 at 17:16
  • I do have 2 dropdowns in the screen.. by default I want to display the first index of the array.. for example, France and Paris should be selected – a.p. patel Feb 07 '20 at 17:17
  • @ Sam , I tried the same but not working as expected.. do you mean I need to created one more option field? – a.p. patel Feb 07 '20 at 17:20
  • 1
    @atitpatel: Maybe [this](https://stackoverflow.com/questions/41117375/angular2-select-default-first-option) can help. – Nicholas K Feb 07 '20 at 17:23
  • This will do the trick : ` ` – Nicholas K Feb 07 '20 at 17:52
0

The input needs to have a value defined. Additionally when you construct the FormGroup you can define a default value if you would like.

This question might help you more. Angular 5 Reactive Forms - Radio Button Group

 <div *ngIf="places?.length > 0" class="col-12">
            <div style=" padding-top: 1em; ">
                <label  *ngFor="let place of places">
                    <input  formControlName="place" type="radio" value=place>{{place}}
                </label>
            </div>
        </div>
Zen
  • 377
  • 1
  • 3
  • 11
0

places = ['effil tower','new discover']

new FormGroup({place: new FormControl(this.places[0])});
 <div *ngIf="places?.length > 0" class="col-12">
            <div style=" padding-top: 1em; ">
                <label  *ngFor="let place of places">
                    <input  formControlName="place" type="radio" [value]="place">{{place}}
                </label>
            </div>
        </div>

Hope this helps. [value]="place" and FormControl(this.places[0])

Jijeesh
  • 26
  • 2