【问题标题】:Angular2 get values of dynamically created inputsAngular2获取动态创建的输入值
【发布时间】:2017-03-24 20:33:44
【问题描述】:

我有这个输入是从列表column 动态创建的,现在我需要在某些方法发生时获取输入的所有值(想象getAllValues()

      <div *ngFor="let cell of column; let i = index;">
              <!-- Material design input-->
              <md-input type="{{cell.type}}" 
                 value="{{getInputValue(cell)}}" 
                 [placeholder]="cell.label">
              </md-input>
      </div>

获取所有生成的输入值的 angular2 方式是什么?

【问题讨论】:

  • 可以使用 ViewChildren,如果它是表单的一部分,它们可以以编程方式(反应式)或魔法(模板驱动)附加到表单中。
  • @silentsod 最佳实践是什么?反应还是魔法?
  • 模板驱动或多或少符合 Angular 1 的做事方式,反应式在代码方面更重,但使单元测试更容易。两者都不是最佳实践,就学习和实际代码行而言,模板驱动可能是一种开销较低的方法。如果它在表单之外,那么您可能需要执行 ViewChildren 查询来获取它们。
  • @siletsod 是的,它们超出了形式,如何使用 ViewChildren 获取所有值是否可以根据 let i = index 获取值?
  • 如果我有时间,我会看看如何制作一个演示 plunker。同时,希望 cmets 能够帮助其他潜在响应者制定适合您使用的解决方案。

标签: angular angular-material angular2-template angular2-directives angular2-material


【解决方案1】:

最简单的方法是使用 ngForm

<form #myForm="ngForm">
      <div *ngFor="let cell of column; let i = index;">
          <md-input [type]="cell.type" 
             [name]="cell.name"      <!-- Note the 'name' has to be set -->
             [ngModel]="cell.value"
             [placeholder]="cell.label"></md-input>
      </div>
      <a (click)="getAllValues(myForm)">print values</a>
</form>

然后您将可以访问 getAllValues() 函数中的 myForm.form.value 对象。 公众号:https://plnkr.co/edit/84mzcNJliMmvszPq3xMm?p=preview

【讨论】:

    【解决方案2】:

    我所做的是:

                  <md-input #input  // NOTICE #input
                              type="{{cell.type}}"
                              value="{{getInputValue(cell) || '--'}}"
                              [placeholder]="cell.label"></md-input>
    

    在组件类中:

    export class MyComponent {
    
        @ViewChildren('input') inputs;
    
    
        public updateData(): void {
            console.log(this.inputs) //this will give access to id and values (explore it on google chromes console)
            console.log(this.inputs.toArray().map(x => x.value)) // this gives access to values
        }
    }
    

    【讨论】:

    • 在动态生成输入(例如使用 ngFor 语句)时,不能以这种方式使用模板变量
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2020-08-24
    • 2018-04-12
    相关资源
    最近更新 更多