2016-07-25 50 views
4

我想使呈现为多个表行的角度2中的TableRowsComponent。表中角度为2的组件中的行

我想在这样的一个模板来使用它:

<table class> 
    <tbody> 
     <table-rows *ngFor="#item of list" [someInput]="item"></table-rows> 
    </tbody> 
</table> 

(因此,“表行”将是这里的TableRowsComponent的选择)的TableRowsComponent的模板会是这样的:

<tr> 
    <td> foo </td> 
    <td> bar </td> 
</tr> 
<tr *ngIf="something"> 
    .... 
</tr> 
<tr *ngFor=".."> 
    ... 
</tr> 

如果我们做到这一点,那么结果是这样的:

<table class> 
     <tbody> 
      <table-rows> 
       <tr> 
        ... 
       </tr> 
       <tr> 
        ... 
       </tr> 
      </table-rows> 
      <table-rows> 
       <tr> 
        ... 
       </tr> 
       <tr> 
        ... 
       </tr> 
      </table-rows> 
     </tbody> 
</table> 

不幸的是,< table-rows>元素混淆了表格的渲染。如何解决这个问题呢?有没有办法让angular2不能渲染<表行>元素?

+0

你可能想看看这个http://stackoverflow.com/questions/38463346/angular2-formgroup-inside-tr-child -component/38470631#3847​​0631 –

+0

感谢您的参考。这几乎是一个很好的解决方案,但是如果您检查plunkr,那么解决方案中的每个< tr > ... < /tr >都在其自己的< tbody > ... < /tbody > :( –

回答

0
import { Component, Input, OnChanges } from '@angular/core'; 
import { FormGroup, FormBuilder, NgForm, REACTIVE_FORM_DIRECTIVES, Validators } from '@angular/forms'; 

    @Component({ 
     selector: '[dependent-row]', 
     providers: [], 
     template: ` 
     <tr [formGroup]="dependentForm"> 
      <td> 
      <input type="text" formControlName="foo"> 
      </td> 
      <td> 
      <input type="text" formControlName="bar"> 
      </td> 
     </tr> 
     `, 
     directives: [REACTIVE_FORM_DIRECTIVES] 
    }) 
    export class DependentRowComponent implements OnChanges { 
     @Input() dependent: any; 
     _Form: any; 

     constructor(fb: FormBuilder) { 
     this.dependentForm = fb.group({ 
      foo: [''], 
      bar: [''], 
     }) 
     } 

     ngOnChanges() { 
     this._Form.find('foo').updateValue(this.dependent.foo); 
     this._Form.find('bar').updateValue(this.dependent.bar); 
     } 
    } 
+1

)这很好,您提供了解决方案,但答案应始终包含一些解释以及代码。谢谢! – Alex

+1

尽管这段代码片段是受欢迎的,并且可能会提供一些帮助,但如果它包含一个解释,它会[大大改进](// meta.stackexchange.com/q/114762)*如果没有这个答案,你的答案就没有什么教育价值了 - 记住你将来会为读者回答这个问题,而不仅仅是这个人现在问的问题!请[编辑]你的回答以添加解释,并给予表明适用的是什么限制和假设。 –

2

命名您的选择时,你可以使用[table-rows]而非table-rows

例如

`@Component({ 
    moduleId: module.id, 
    selector: '[table-rows]', 
    templateUrl: 'table-rows.component.html' 
})` 

,然后只需在TBODY标签内使用它,ALA <tbody table-rows></tbody>