check radio button in angular 2 when there is ngModel

荒凉一梦 提交于 2021-02-07 08:47:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!