Search code examples
javascriptangulartypescriptangular7ngfor

Radio buttons in Template-Driven Forms


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)" autocomplete="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}}

Solution

  • You 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.