获取动态输入字段的值

时间:2018-09-05 14:44:06

标签: html angular

我有这个HTML模板:

    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div data-role="dynamic-fields">
                    <div class="form-inline">
                        <div class="form-group">
                            <label class="sr-only" for="field-name">Link </label>
                            <input type="text" class="form-control" id="field-name" placeholder="Link" 
                            [(ngModel)]="HrefLink" name="HrefLink">
                        </div>
                        <span>-</span>
                        <div class="form-group">
                            <label class="sr-only" for="field-value">Label</label>
                            <input type="text" class="form-control" id="Label" placeholder="Label" 
                            [(ngModel)]="HrefLabel" name="HrefLabel">
                        </div>
                        <button class="btn btn-danger" data-role="remove">
                            <span class="glyphicon glyphicon-remove"></span>
                        </button>
                        <button class="btn btn-primary" data-role="add">
                            <span class="glyphicon glyphicon-plus"></span>
                        </button>
                    </div>  <!-- /div.form-inline -->
                </div>  <!-- /div[data-role="dynamic-fields"] -->
            </div>  <!-- /div.col-md-12 -->
        </div>  <!-- /div.row -->
    </div>

以这种简单的形式,我可以添加一个或多个输入。这是实时示例:https://bootsnipp.com/snippets/VPRlZ

我的问题是:如何获取angular component中所有已添加字段的值?我可以在每个输入中像上面一样添加指令ngModel,但是所有指令都具有相同的名称,我不会得到所有值吗? 不幸的是,我无法将ngModel的{​​{1}}中的div放在更高的位置... 请告诉我我的问题是否明确或者您需要更多信息。

1 个答案:

答案 0 :(得分:0)

为什么不将输入量基于Objects数组(InputModel是自定义接口或类),最后使用* ngfor来显示它们。

InputModel

{
  input_value: string,
  index_of: number,
  isDelete: boolean, //if false is "+" if true is  "x"
}

Component.ts

inputValues: InputModel[] = [];
count: number = 0;

OnInit{
  this.inputValues.push({
      input_value:"",
      index_of: this.count,
      isDelete: true
  });
}
addMore(){
   this.inputValues.push({
      input_value:"",
      index_of: this.count++,
      isDelete: false
  });
}

HTML模板

<div *ngFor="let input of inputValues">
    <input [(ngModel)]="input.input_value" />
    <!-- TODO button with 'x' or '+' depends of input.isDelete -->
</div>
相关问题