【问题标题】:Angular input form into *ngFor*ngFor 的角度输入表单
【发布时间】:2017-09-24 08:55:09
【问题描述】:

当我需要表格的<tr> 标签内的<input> 标签,而<tr> 标签是由*ngFor 生成时,我对如何使用Angular 2 有点困惑。我的情况是这样的:我有一系列“产品”,我应该在<tr> 标签上显示产品信息,并且对于每个产品,一个input 字段以增加每个产品的库存。这就是我所做的:

ProductStokeComponent.ts

export class ProductStokeComponent implements OnInit {

  form: FormGroup;
  products: Subject<Product[]> = new Subject();

  constructor(
    private productService: ProductService,
    private formBuilder: FormBuilder,
  ) { }

  ngOnInit() {
    this.formInit();
    this.getProducts();
  }

  formInit() {
    this.form = this.formBuilder.group({
      products: this.formBuilder.array([])
    });
  }

  getProducts() {
    this.productService.getProducts().subscribe(data => {
      this.products.next(data);
    });
  }

}

ProductStokeComponent.html

<form [formGroup]="form" (ngSubmit)="formSubmit()">
  <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Stock</th>
        <th>Stock Entrance</th>
      </tr>
    </thead>
    <tbody formArrayName="products">
      <tr *ngFor="let product of products| async">
        <td>{{ product.id }}</td>
        <td>{{ product.name }}</td>
        <td>{{ product.stock }}</td>
        <td>
          <input type="number" name="stock[product.id]" >
        </td>
      </tr>
    </tbody>
  </table>
  <button type="submit">Add Stock</button>
</form>

在纯 html 上,我能够取消命名数组,但在 Angular 2 中,我尝试使用反应式表单,但随后我应该使用 for 循环在循环后填充表单以生成表格对于每个产品来说,这听起来像是使用大量资源来做一件简单的事情。

使用反应形式的方法更新

ProductStokeComponent.ts

ngOnInit() {
    this.formInit();
    this.getProducts();
}

formInit(product?: Product) {
    this.form = this.formBuilder.group({
      products: this.formBuilder.array([])
    });
}

ProductStokeComponent.html

<tbody formArrayName="products">

【问题讨论】:

  • 想法是在input 中放入要添加到库存中的元素数量?
  • 是的,应该是输入数字

标签: angular typescript angular2-forms


【解决方案1】:

反应式解决方案如下所示:

    <tr *ngFor="let product of form.controls['products'].controls">
        <td>{{ product.value.id }}</td>
        <td>{{ product.value.name }}</td>
        <td>{{ product.value.stock }}</td>
        <td>
            <input #moreStock>
            <button (click)="addMoreStock(product.value, moreStock.value)">+</button>
        </td>
    </tr>

或者如果你想要模板表单解决方案:

<tbody>
  <tr *ngFor="let product of products">
    <td>{{ product.id }}</td>
    <td>{{ product.name }}</td>
    <td>{{ product.stock }}</td>
    <td>
      <input #moreStock>
      <button (click)="addMoreStock(product, moreStock.value)">+</button>
    </td>
  </tr>
</tbody>

在这两种情况下,在你的 TypeScript 文件中添加这样的方法:

public addMoreStock(product, howMuch)
{
    product.stock += parseInt(howMuch, 10);
}

【讨论】:

  • 在此表单上,我将使用对象产品的属性,我将如何处理反应式表单,我使用反应式或在这种情况下使用反应式表单不是一个好主意?跨度>
  • 我的问题是,我如何在 form.controls['products'].controls 上获得产品的值,我将从表单中的产品数组中填写所有内容,但只会使用新的股票价值如何输入数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 2018-04-12
  • 2016-08-01
  • 2017-08-05
  • 2018-09-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多