问题
In my Angular 2 project there is ngModel
and the radio button doesn't check it
<input type="radio" id="user" name="user" value="RETAIL" [(ngModel)]="myRadio" check>
But when I cut the ngModel
it check
<input type="radio" id="user" name="user" value="RETAIL check>
But I can't cut it because I need ngModel
, is there another way to check radio button on the load page with ngModel
?
回答1:
If the value of the input element is a string literal, declare it using one of the two following forms:
<input type="radio" id="user" name="user" value="My value 1" [(ngModel)]="myRadio" />
<input type="radio" id="user" name="user" [value]="'My value 1'" [(ngModel)]="myRadio" />
If the value is not a string literal, use [value]
:
<input type="radio" id="user" name="user" [value]="MyValue1" [(ngModel)]="myRadio" />
To have the radio button selected by default, you should initialize myRadio
to the appropriate value:
For a string value:
public myRadio: string = "My value 1";
For another type of data:
public myRadio: MyDataType = MyValue1;
You see the code at work in this plunker.
回答2:
You’re missing the binding on the check attribute. You just need this
<input type=“radio” id=“user” name=“user” value=“RETAIL” [(ngModel)]=“myRadio” [checked]=“true”>
I’ve placed the true because you asked for it to be checked upon page load. But instead of true you can put a variable or a condition if you want it to have a bit more logic behind.
You can have a quick look here to check a bit more options on how to setup a radio button on Angular
回答3:
The following should work
<input type="radio" name="user" [value]="RETAIL" [(ngModel)]="myRadio">
来源:https://stackoverflow.com/questions/47941071/check-radio-button-in-angular-2-when-there-is-ngmodel