Every time the page loads the last radio button is always checked. I know it has something to do with Id but I cannot figure out how to solve it.
countryArray
countryA = [{name : "Finland"}, {name : "china"},{name : "USA"}]
test.html
<form #filterForm="ngForm" (ngSubmit)="addFilter(filterForm)" autoplete="off">
<div class="row">
<div class="col-12" style="border: 1px solid red">
<div *ngFor="let x of country">
<label for="{{x.name}}"> {{x.name}} </label>
<input type="radio" id="{{x.name}}" value="{{x.name}}" name="countries" [(ngModel)]='x.name' >
</div>
</div>
<!-- <div class="col-12" style="border: 1px solid red">b</div>
<div class="col-12" style="border: 1px solid red">c</div>
<div class="col-12" style="border: 1px solid red">D</div> -->
</div>
</form>
hh : {{filterForm.value | json}}
Every time the page loads the last radio button is always checked. I know it has something to do with Id but I cannot figure out how to solve it.
countryArray
countryA = [{name : "Finland"}, {name : "china"},{name : "USA"}]
test.html
<form #filterForm="ngForm" (ngSubmit)="addFilter(filterForm)" autoplete="off">
<div class="row">
<div class="col-12" style="border: 1px solid red">
<div *ngFor="let x of country">
<label for="{{x.name}}"> {{x.name}} </label>
<input type="radio" id="{{x.name}}" value="{{x.name}}" name="countries" [(ngModel)]='x.name' >
</div>
</div>
<!-- <div class="col-12" style="border: 1px solid red">b</div>
<div class="col-12" style="border: 1px solid red">c</div>
<div class="col-12" style="border: 1px solid red">D</div> -->
</div>
</form>
hh : {{filterForm.value | json}}
Share
Improve this question
edited Dec 14, 2019 at 16:36
JFoxx64
2622 silver badges11 bronze badges
asked Dec 14, 2019 at 13:11
MenimEMenimE
3141 gold badge7 silver badges19 bronze badges
0
2 Answers
Reset to default 5You should add a selected property to each country to use as ngModel for value of radio button:
in constructor:
this.country = this.country.map(item =>({ name: item.name , selected : false }));
in html:
<div class="col-12" style="border: 1px solid red">
<div *ngFor="let x of country; index as i">
<label for="{{x.name}}"> {{x.name}} </label>
<input type="radio" id="{{x.name}}" value="{{x.name}}" name="countries" [(ngModel)]="country[i].selected">
</div>
</div>
check demo.
You are applying ngModel
to 'x.name' and it is a reason why it is checked. You can create a variable selectedRadio
and assign value of radio button:
<div *ngFor="let x of country">
<label for="{{x.name}}"> {{x.name}} </label>
<input type="radio"
id="{{x.name}}"
value="{{x.name}}"
[(ngModel)] ="selectedRadio"
name="countries">
</div>
<p> {{ selectedRadio | json }} </p>
TypeScript:
selectedRadio: any;
A stackblitz example can be seen here.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745345065a4623505.html
评论列表(0条)