【问题标题】:Using template with nested ngfor使用带有嵌套 ngfor 的模板
【发布时间】:2017-04-27 00:40:46
【问题描述】:

使用 Angular4 ReactiveForm(我正在使用的版本)创建一个表单。 我在哪里有一个包含代码、年份和类别列表的表单。

主窗体:

  • 代码
  • 年份
  • 类别[]
    • 代码
    • 描述
    • 订购
    • 产品[]
      • 代码
      • 描述
      • 价格

但我试图以以下方式显示表单,其中类别列表和每个类别中的产品都是行,并且都将显示在同一个表中(示例):

<input code>
<input year>
<table>
<tr>Category 1</tr>
<tr>Product 1.1</tr>
<tr>Product 1.2</tr>
<tr>Product 1.3</tr>
<tr>Category 2</tr>
<tr>Product 2.1</tr>
<tr>Product 2.2</tr>
</table>
<button addNewCategory />
<button addNewProduct />

我可以将类别显示为行,但我无法将每个类别中的产品显示为类别行下方的一行:

我的打字稿表格:

ngOnInit() {
    this.form = this._fb.group({
        code: ['', Validators.required],
        year: ['', Validators.required],
        categories: this._fb.array([this.initCategory()])
    });
}

initCategory() {
    return this._fb.group({
        code: ['', Validators.required],
        desc: ['', Validators.required],
        order: ['', Validators.required],
        products: this._fb.array([this.initProduct()])
    });
}

initProduct() {
    return this._fb.group({
        code: ['', Validators.required],
        desc: ['', Validators.required],
        price: ['', Validators.required]
    });
}

搜索,有人告诉我用ngfor模板,但是我不能用,当我尝试用的时候,模板标签里面的内容没有显示出来。

如果我使用 div,我可以在每个类别下方显示产品。但它在表格中效果不佳。

我的模板:

<div>
<form [formGroup]="form">
    <input type="text" formControlName="code" />
    <input type="text" formControlName="year" />
    <table>
        <div formArrayName="categories">
        <template *ngFor="let category of form.controls['categories'].controls; let i=index">
            <tr>
                <td><input type="text" formControlName="code" /></td>
                <td><input type="text" formControlName="desc" /></td>
                <td><input type="text" formControlName="order" /></td>
            </tr>
            <div="products">
            <template *ngFor="let product of category.controls['products'].controls; let j=index">
                <tr>
                    <td><input type="text" formControlName="code" /></td>
                    <td><input type="text" formControlName="desc" /></td>
                    <td><input type="text" formControlName="price" /></td>
                </tr>
            </template>
            </div>
        </template>
        </div>
    </table>
</form>
</div>

【问题讨论】:

  • 嘿,我的回答对你有用吗?

标签: angular templates typescript reactive-forms


【解决方案1】:

首先,您应该使用 ng-template,因为 template 在 v4 中已被弃用。

如果您查看浏览器的控制台,您可能会看到如下错误:

错误错误:找不到带有路径的控件:'ARRAY_NAME -> FORM_CONTROL_NAME'

要修复它,您必须将 category 包装为 formGroupName

<tr [formGroupName]='i'>
  ...
</tr>

对于products

<div="products" formArrayName="products">
  ...
      <tr [formGroupName]='j'>
        ...
      </tr>
  ...
</div>

如果您的 component 文件中的所有内容都正确,它应该可以工作。

【讨论】:

    猜你喜欢
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多