Angular 2 check radio button by default

2020-02-14 07:16发布

问题:

I am trying to check my radio button with zero value by default. I am trying to use the [checked]='true' attribute. But that does not work.

<input type="radio" name="unitTrusts-pnl" id="unitTrusts-pnl0" class="with-gap" [value]="0" [(ngModel)]="unitTrustsPnl"  [checked]='true'>
<input type="radio" name="unitTrusts-pnl" id="unitTrusts-pnl0" class="with-gap" [value]="1" [(ngModel)]="unitTrustsPnl">

DEMO

https://stackblitz.com/edit/angular-jj9gib

回答1:

Since the buttons are bound to a variable, try setting the variable instead :

unitTrustsPnl = 0;


回答2:

Each of you'r radio buttons have an attribute calld value, that means if you set ngModel's value (unitTrustsPnl) to each radio's value, that radio will be checked.

Eg you have

<input type="radio" name="unitTrusts-pnl" id="unitTrusts-pnl0" class="with-gap" [value]="0" [(ngModel)]="unitTrustsPnl">

So if you set unitTrustsPnl value to 0 , this radio will check and so on.

Update : You'r variable (unitTrustsPnl) should be in type of number, declare it like

public unitTrustsPnl: number;

Its reason is because you mentioned [value]="0" HTML considered that you have a number type variable.



回答3:

Try adding this in addition to the [checked] you already have:

[attr.checked]="true"


回答4:

Do something like [(ngModel)]=“variableWithZeroValue” [checked]=“variableWithZeroValue==0? true: false” and initialize variableWithZeroValue=0 in the constructor of the class.

But, this will always check the checkbox whenever the variableWithZeroValue has value equal to zero.

Hope, it helps.



标签: angular