2016-12-25 84 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

相关问题