【问题标题】:Using @ngFor templates for radio button generation使用 @ngFor 模板生成单选按钮
【发布时间】:2017-04-10 06:49:55
【问题描述】:

我有以下代码,我想使用 *ngFor。该代码仅显示 2 个单选按钮,但还有更多。

  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 库的语法如下:

  <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>

【问题讨论】:

    标签: angular angular2-forms


    【解决方案1】:

    问题是您使用option 作为模板变量名以及*ngFor 当前迭代值。这就是为什么*ngFor#option 模板的radio 元素覆盖的原因。

    您应该更改变量名称之一,假设 *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

    【讨论】:

    • 一开始包装它时我自己也是这么想的——我确实有 type='radio'。然而,它没有。没有错误。什么都没有显示。我把所有东西都放在一个 div 中并带有一个标签。标签显示,但没有来自 *ngFor 模板。请记住我在 http://materializecss.com/forms.html#radio 使用的库的语法 &lt;input class="with-gap" name="group3" type="radio" id="test5" checked /&gt; &lt;label for="test5"&gt;Red&lt;/label&gt;l
    • 参见上面的 EDIT1
    • 参见上面的 EDIT2。对不起。请注意,在库示例中,标签是在单选按钮之后创建的,而不是与标签一起包装。我怀疑这是问题所在,但我不确定如何做到这一点。
    • @st_clair_clarke 检查更新的答案,变量声明命名冲突中有错误。一个变量已被第二个覆盖。因为它们被初始化了两次
    【解决方案2】:

    如果你至少使用 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>
    

    注意 " 而不是 ' 并且不要这样做 for='option' 的东西!

    【讨论】:

    • 抱歉,没有显示任何内容。我正在使用角度〜2.1.2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 2017-05-31
    • 2017-09-20
    • 2021-09-28
    • 2020-07-05
    • 2013-11-27
    相关资源
    最近更新 更多