I am not sure why I am getting two different values in my component. When I click first time on Shift A, then I am getting value as 2, then when I click again, I am getting 1. Any ideas why it is so...
Also I want to select Shift A when the page loads. Thanks in advance for your help!!
lineside-monitor.component.html:
<div class="box">
<div class="row moveright">
<div>
Shift A <input type="radio" name="shiftRadioGroup" [value]="1" [(ngModel)]="shiftRadioBtn" (click)="popuplateBySearchFilter(1)">
</div>
<div class="notsotall"> </div>
<div>
Shift B <input type="radio" name="shiftRadioGroup" [value]="2" [(ngModel)]="shiftRadioBtn" (click)="popuplateBySearchFilter(2)">
</div>
</div>
</div>
lineside-monitor.component.ts
@Component({
selector: 'app-lineside-monitor',
templateUrl: './lineside-monitor.component.html',
styleUrls: ['./lineside-monitor.component.css']
})
export class LinesideMonitorComponent implements OnInit {
public shiftRadioBtn: string;// = "1";
ngOnInit() {
this.shiftRadioBtn="1";
}
popuplateBySearchFilter(modelId: number) {
alert(this.shiftRadioBtn);
}
}
Since you are considering those radio button value as string
, use value
attribute instead of [value]
(attribute binding). Otherwise you have to set initial shiftRadioBtn
value to be 1
(number) rather than "1"
(string)
Also for getting correct value to be printed on change of radio button selection, use change
event instead of click
event.
<div>
Shift A
<input type="radio" name="shiftRadioGroup" value="1"
[(ngModel)]="shiftRadioBtn" (change)="popuplateBySearchFilter(1)" />
</div>
<div class="notsotall">
</div>
<div>
Shift B
<input type="radio" name="shiftRadioGroup" value="2"
[(ngModel)]="shiftRadioBtn" (change)="popuplateBySearchFilter(2)" />
</div>
Running Stackblitz Demo
Why? because you're binding the model in two-way mode to the radio button, so whenever you click the radio button automatically it changes the shiftRadioBtn
model base on the [value]
in the radio button.
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.