2017-04-27 175 views
2

使用Angular4 ReactiveForm(我使用的版本)創建表單。 我在哪裏有表格,其中有代碼,年份和類別列表。使用嵌套ngfor模板

主要形式:

  • 代碼
  • 分類[]
    • 代碼
    • 說明
    • 訂購
    • 產品[]
      • 代碼
      • 說明
      • 價格

但我想表現在以下方式的形式,在類別列表和產品在每個類別將是所有行,並將全部顯示在同一個表中(示例):

<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模板,但我不能使用它們,當我嘗試使用它們時,模板標記內的內容不顯示。

如果我使用divs,我可以在每個類別下面顯示產品。但是它在桌子內並不能很好地工作。

我的模板:

所有的
<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> 
+0

嘿,我的答案是否適合你? – developer033

回答

2

首先,你應該使用ng-template因爲template在V4被廢棄。

也許如果你看看到瀏覽器的控制檯,你會看到這樣的錯誤:

ERROR Error: Cannot find control with path: 'ARRAY_NAME -> FORM_CONTROL_NAME'

要解決它,你必須包裹categoryformGroupName

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

併爲products

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

它應該工作,如果它的每一個請在你的component文件中更正。