使用 *ngFor 使用 materialize-css 框架为 angular2 创建一系列单选按钮

Using *ngFor for create a series of radio buttons for angular2 using materialize-css framework

大家节日快乐!

我有以下代码基于 materialize-css 框架构建单个单选按钮 http://materializecss.com/forms.html#radio

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

我尝试使用 *ngFor 如下所示:

  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>

已创建所有按钮,但只能选择第一个按钮(单个)。

如何让一系列按钮发挥单选按钮的预期功能?

谢谢

Plunker

为什么它不起作用

*ngFor 循环中的 status 变量未在 labelfor 属性或 id 属性中使用 input.

有两个选项可以解决此问题:

Template expressions

您可以通过将属性放在方括号中来使用模板表达式,如下所示:

<input [id]="status">

这是您对 value 属性所做的(正确)操作。

A template expression produces a value. Angular executes the expression and assigns it to a property of a binding target; the target might be an HTML element, a component, or a directive.

Interpolation

您可以像这样使用双花括号来使用插值:

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

More generally, the material between the braces is a template expression that Angular first evaluates and then converts to a string.

有什么区别?

查看 了解这些方法之间的区别。

完整模板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() { }

}

更新 - Angular 2 个版本 < 2.2.0

如果您使用的 Angular 2 版本低于 2.2.0,您需要明确设置 labelfor 属性,如下所示:

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

因为 for 不是 label 个元素的 属性。

为什么?

因为 Angular 2.2.0 (634b3bb), Angular 将 for 属性映射到相关的 htmlFor 属性.

听起来很多开发者直觉expected this,所以他们添加了它。

一开始这让我很困惑,Pascal Precht 的 this article 确实解决了很多问题。