2016-11-25 38 views
1

我有以下代碼,我想使用* ngFor。該代碼只顯示2個單選按鈕,但還有更多。使用@ngFor模板生成單選按鈕

options: string[] = [ 
    'Single', 
    'Married', 
    'Divorced', 
    'Common-law', 
    'Visiting' 
    ]; 

<input 
    #single 
    class = 'with-gap' 
    name = 'group3' 
    type = 'radio' 
    id = 'single' 
    value = 'Single' 
    (change) = 'radioBtnChange$.next(single.value)'/> 
<label for = 'single'>Single</label> 

<input #married 
     class = 'with-gap' 
     name = 'group3' 
     type = 'radio' 
     id = 'married' 
     value = 'Maried' 
     (change) = 'radioBtnChange$.next(married.value)'/> 
<label for = 'married'>Married</label> 

而不是寫個人單選按鈕的,我怎麼可能用@ngFor因此代碼可以更簡潔。

EDIT1 的libarary的語法如下:

<input class="with-gap" name="group3" type="radio" id="test5" checked /> 
    <label for="test5">Red</label> 

這是http://materializecss.com/forms.html

我已經試過包裝在標籤中輸入,但只有標籤被顯示的部分。

感謝任何輸入。

EDIT2

<label *ngFor="let option of options" for='option' > 
    <input 
     #option 
     type="radio" 
     class = 'with-gap' 
     name='group3' 
     id='option' 
     [value]='option' 
     (change) = 'radioBtnChange$.next(option.value)'/> 
    </label> 

回答

1

的問題是您正在使用option作爲模板變量名稱以及*ngFor當前迭代值。這就是爲什麼*ngFor被元素的#option模板覆蓋的原因。

你應該改變的變量名中的一個,假設*ngFor="let option of options"*ngFor="let opt of options"

標記

<label *ngFor="let opt of options" for='option' > 
    <input 
     #option 
     type="radio" 
     class = 'with-gap' 
     name='group3' 
     id='option' 
     [value]='option' 
     (change) = 'changed(opt)'/> 
</label> 

Demo Here

+0

和以前一樣,當我嘗試它時,什麼都不顯示 –

+0

它應該工作,發生了什麼? –

+0

我自己當初是這麼想的 - 當時我把它包裹起來 - 我的確有類型='收音機'。但是,它沒有。沒有錯誤。沒有顯示。我把一個div和一個標籤換成了。該標籤顯示,但沒有任何* ngFor模板。請記住我正在使用的庫的語法 l'在[http://materializecss.com/forms.html](http://materializecss.com/forms.html)#radio –

0

如果u使用至少Angular2 RC2我認爲,應該工作:

<label *ngFor="let option of options"> 
    <input 
    #option 
    type="radio" 
    class = "with-gap" 
    name="group3" 
    id="option" 
    [value]="option" 
    (change) = "radioBtnChange$.next(option.value)"/> 
</label> 

請注意「而不是」,不要這樣做='選項'的東西!

+0

對不起,但沒有顯示。我正在使用角~2.1.2 –