2017-05-04 319 views
7

我試圖將標記爲默認的radiobutton取決於我從我的對象獲得的值,可以是True或False。 如何根據選項標記爲默認單選按鈕?Angular 4默認radioButton默認設置

 <label>This rule is true if:</label> 
     <label class="form-check-inline"> 
     <input class="form-check-input" type="radio" name="mode" 
     value="true" [(ngModel)]="rule.mode"> all the following conditions are true 
     </label> 
     <label class="form-check-inline"> 
     <input class="form-check-input" type="radio" name="mode" value="false" [(ngModel)]="rule.mode"> at least one of the following conditions is true 
     </label> 

我得到了真或假:「rule.mode」

+2

[attr.checked] = 「role.mode」 –

+0

@BharatChauhan這是一個正確的答案,完美的 '初始化只' 設置的值。謝謝! – CularBytes

回答

12

您可以使用[(ngModel)],但你需要更新你的value[value]否則該值評估爲字符串。它應該是這樣的:

<label>This rule is true if:</label> 
<label class="form-check-inline"> 
    <input class="form-check-input" type="radio" name="mode" [value]="true" [(ngModel)]="rule.mode"> 
</label> 
<label class="form-check-inline"> 
    <input class="form-check-input" type="radio" name="mode" [value]="false" [(ngModel)]="rule.mode"> 
</label> 

如果rule.mode是真的,那麼無線電選擇。如果它是錯誤的,那麼另一個。

差異真的歸結爲valuevalue="true"的計算結果爲字符串'true',而[value]="true"的計算結果爲布爾值true。

+0

謝謝你,我的日子!^^ – XGuy

+0

謝謝,你救了我的一天! – Buminda

-1

我認爲這應該工作:

<label>This rule is true if:</label> 
<label class="form-check-inline"> 
    <input class="form-check-input" type="radio" name="mode" [value]="true" [(ngModel)]="rule.mode"> 
</label> 
<label class="form-check-inline"> 
    <input class="form-check-input" type="radio" name="mode" [value]="false" [(ngModel)]="rule.mode"> 
</label>