2016-12-25 61 views
3

季節問候大家!使用* ngFor創建一系列使用materialize-css框架的angular2單選按鈕

我有如下所示的代碼,在使用* ngFor構建了基於該物質化,CSS框架http://materializecss.com/forms.html#radio

<input name = 'group1' 
     type = 'radio' 
     id = 'test2'/> 
<label for = 'test2'>Yellow</label> 

我嘗試一個單選按鈕:

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

    <p>{{maritalStatus?.status}}</p> 
    <div *ngFor = 'let status of statuses; let indx = index'> 
    <input #widget 
      class = 'with-gap' 
      name = 'statusGroup' 
      type = 'radio' 
      id = 'status' 
      [value] = 'status' 
      [(ngModel)] = 'maritalStatus.status' 
      (change) = 'radioBtnChange$.next(status)' 
    /> 
    <label for = 'status'>{{status}}</label> 
    <p>{{status}}{{ indx}}</p> 
    </div> 

所有按鈕被創建,但只有第一個按鈕(單)可以被選中。

如何獲得一系列的按鈕功能作爲單選按鈕的功能?

感謝

回答

4

Plunker

爲什麼它不工作

status變量在*ngFor循環沒有在for屬性您label或您inputid屬性被使用。

有兩個選項來解決這個:

Template expressions

您可以通過將方括號中的屬性,這樣使用模板表達式:

<input [id]="status">

這就是你(正確)與value屬性。

模板表達式產生一個值。 Angular執行表達式並將其分配給綁定目標的屬性;目標可能是HTML元素,組件或指令。

Interpolation

可以通過使用雙花括號像這樣使用插值:

<input id="{{status}}">

更一般地,括號之間的材料是一個模板表達式角第一評估並轉換爲字符串。

有什麼區別?

結帳this answer瞭解這些方法之間的差異。

完整的HTML模板

<h2>Current Status</h2> 
<p>{{maritalStatus?.status}}</p> 

<h2>Options</h2> 
<div *ngFor="let status of statuses; let indx = index"> 
    <input #widget 
    class='with-gap' 
    name='statusGroup' 
    type='radio' 
    [id]='status' 
    [value]='status' 
    [(ngModel)]='maritalStatus.status' 
    /> 
    <label [for]='status'>{{status}}</label> 
</div> 

全部組件

import {Component} from '@angular/core'; 
import {Http} from '@angular/http' 
import {bootstrap} from '@angular/platform-browser-dynamic'; 

@Component({ 
    selector: 'material-app', 
    templateUrl: 'app.component.html' 
}) 
export class AppComponent { 
    maritalStatus = { status: 'Nothing selected' }; 
    statuses: string[] = [ 
    'Single', 
    'Married', 
    'Divorced', 
    'Common-law', 
    'Visiting' 
    ]; 
    constructor() { } 

} 

更新 - 角2個版本2.2.0 <

如果您使用的是角2版本低於2.2 .0您需要明確設置labelfor屬性,如下所示:

<label [attr.for]='status'>{{status}}</label> 

因爲for不是label元素的屬性。

爲什麼?

由於Angular 2.2.0634b3bb),Angular將for屬性映射到相關的htmlFor屬性。

這聽起來像很多開發人員直觀地expected this,所以他們添加它。

這一切對我來說都很讓人困惑,Pascal Precht的this article真的解決了很多問題。

+0

太好了,謝謝。爲了讓它運行,我必須做兩個小小的調整 - 輸入和標籤上的id都是屬性,而不是屬性。因此我必須在attr前加上它才能工作。請參閱上面的EDIT1,瞭解適合我的東西。謝謝 –

+0

實際上,只需進行一次調整即可,因爲id既是屬性也是屬性。 –

+0

我剛剛發現只有在您使用小於2.2.0的Angular 2版本時才需要。最初我非常困惑,事實證明他們最近添加了這個功能。感謝您指出它,因爲它導致了一些有趣的框架學習! – adriancarriger