【问题标题】:Unable to assign variable from outer ngFor loop to ngModel inside a nested loop无法将外部 ngFor 循环中的变量分配给嵌套循环内的 ngModel
【发布时间】:2017-09-27 02:50:49
【问题描述】:

我面临的问题是使用变量设置 ngModel 的变量名。详细说明:

这里用作“选项”的 json 是:

{
  "a": [
    "a1",
    "a2",
    "a3"
  ],
  "b": [
    "b1",
    "b2",
    "b3",
    "b4"
  ],
  "c": [
    "c1",
    "c2",
    "c3",
    "c4",
    "c5",
    "c6"
  ]
}.

数组 'keys' 由 {"a", "b", "c"} 组成,并已在组件类中使用 -
this.keys = Object.keys(this.options );

我在这里所做的是在 html 页面上为每个键创建不同的选项卡,它们的值作为单选按钮,即选项卡是“a”、“b”和“c”,每个选项卡都有对应的选项值(选项卡 a 上的“a1、a2、a3”,选项卡 b 上的“b1、b2、b3 和 b4”等等)作为单选按钮。它工作到这一步。

尝试将变量设置为键的值(“a”、“b”和“c”)并返回相应的选定单选按钮作为每个选项卡的值时会弹出问题。为了澄清,我想返回 a = a1 或 a2 或 a3 , b = b1 或 b2 或 b3 或 b4 和 c= c1 或 c2 或 c3 或 c4 或 c5 或 c6 (基于我的选择)。我无法将 ngModel 设置为任何相关变量来实现这一点。我可以直接将 ngModel 设置为“a”、“b”或“c”,但不能使用循环变量,例如键或使用索引的访问键。另外,如果它是相关的,我将使用 formGroup 作为这个表单。

任何帮助将不胜感激。我不确定我是否已经解释得足够好,所以请随时提出问题。 (而且我对 Angular 还很陌生,所以我可能错过了一些明显的东西,尽管我已经尝试解决这个问题一段时间了:/)

<div *ngFor="let key of keys">
<md-tab label="{{key}}">

  <fieldset class="fieldset">

    <legend>{{key}}</legend>

    <div class="row">

          <div *ngFor="let opt of options[key]" class="large-3 small-6 columns end">
          <input id="{{opt}}" type="radio" formControlName="{{key}}" value="{{opt}}" [(ngModel)]="key.selected" /> 
          <label for="{{opt}}"><span class="{{opt}}"></span>{{opt}}</label><br/>
        </div>
      </div>
  </fieldset>

</md-tab>

【问题讨论】:

    标签: angular2-forms ngfor angular2-ngmodel


    【解决方案1】:

    这是你的起点:

    添加组件

    public temp = {};
    

    和html

    <div *ngFor="let key of keys">
        <legend>{{key}}</legend>
        <div *ngFor="let opt of options[key]">
            <input id="{{opt}}" type="radio" [name]="key" [value]="opt" [(ngModel)]="temp[key]" />
            <label for="{{opt}}"><span class="{{opt}}"></span>{{opt}}<br/></label>
        </div>
    </div>
    

    【讨论】:

    • 我的组件模型中有类似的东西:any ={};我正在使用其值设置:formControlName="p_weight" [(ngModel)]="model.p_weight" 但是变量有问题(作为“model.key”或使用插值)。使用它作为您提到的索引有效!非常感谢!!
    猜你喜欢
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 2021-01-04
    • 2013-05-25
    相关资源
    最近更新 更多