javascript
  • html
  • angular
  • 2017-05-09 33 views 0 likes 
    0

    我想要獲取一些無線電輸入,其中一個必須預選。如何在Angular中使用雙向綁定時預先選擇單選按鈕?

    以下是代碼:

    <div class='form-group que-box' *ngFor="let option of options"> 
        <input type='radio' id="{{option.optionId}}" name="radio" [(ngModel)]="optionSelected" value='{{option.optionId}}'> 
        <label for='{{option.optionId}}'><span class="que">{{option.text}}</span></label> 
    </div> 
    

    但按鈕沒有得到preselected.I試圖有條件地把checked屬性有,但也不會主動幫助HTML是呈現與checked屬性,但仍該選項沒有預選。我也檢查了optionSelected總是包含理想值。

    回答

    1

    設置optionSelected到要選擇應該工作期權的價值,是這樣的:

    this.optionSelected = option[0].optionId; 
    

    如果optionId是一個數字或其他任何東西不是一個字符串,然後設置使用interpolation值(value='{{ option.optionId }}')將不起作用,因爲它將被評估爲字符串,所以當使用strict equality (===)進行檢查時,它將不匹配optionSelected,Angular在底層使用該選項。

    速戰速決將迫使optionSelected是一個字符串,以及:

    this.optionSelected = option[0].optionId + ''; 
    

    解決這個問題的正確方法是使用data binding設置value屬性。

    在角(角度2和4):

    [value]="optionSelected" 
    

    在AngularJS(角1):

    ng-value="optionSelected" 
    
    +0

    我已經做了類似的東西。 optionSelected在我的代碼中包含有效值。 –

    +0

    @ sudheer-singh當你使用'value'而不是'ng-value'時,這個值總是被解釋爲一個字符串。可能'this.optionSelected =選項[0] .optionId +'';'將起作用。如果你不想這樣做,那麼在你的HTML中使用'ng-value'代替。 – Danziger

    +0

    將'value'改爲'[value]'工作。感謝您指出了這一點。 –

    相關問題