简体   繁体   中英

input type radio checked resets after pages loads

I'm having a input of type radio in a forloop template like this:

    <ng-template ngFor [ngForOf]="numberOfOptions | reverse" let-item>
        <input id="rating{{item}}" type="radio" name="rating" value="{{item}}" [(ngModel)]="alreadySelected" [checked]="item === defaultSelected">
        <label for="rating{{item}}">{{item}}</label>
    </ng-template>

where defaultSelected is a property in my component:

defaultSelected: number

When the page reloads the correct radio is selected but then suddenly it just resets to none selected.

The property was defined as:

set alreadySelected(value) {
    this._alreadySelected = value
    this.notify.emit(value);  
}

But there was no getter for it so I added the getter like this:

get alreadySelected(): number {
    return this._alreadySelected
}

and then the condition for is checked like this:

<input id="rating{{item}}" type="radio" name="rating" [value]="item" [(ngModel)]="alreadySelected" [checked]="item == alreadySelected">

Then when I have a defaultSelected because it's optional:

ngOnInit(): void {
    if (this.defaultSelected) {
        this.alreadySelected = this.defaultSelected
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM