【问题标题】:Table Rows in component in angular 2角度 2 中组件中的表格行
【发布时间】:2017-03-01 22:46:13
【问题描述】:

我想在 Angular 2 中制作一个 TableRowsComponent,它可以呈现为多个表格行。

我想在这样的模板中使用它:

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

(因此“table-rows”将是此处 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>

不幸的是, 元素弄乱了表格的渲染。如何解决这个问题呢?有没有办法让 angular2 不呈现 元素?

【问题讨论】:

  • 感谢您的参考。这几乎是一个很好的解决方案,但如果你检查 plunkr 那里的解决方案有每个 ... tr > 在它自己的 ... tbody > :(

标签: angular angular2-template


【解决方案1】:

在命名选择器时,您可以使用[table-rows] 而不是table-rows

例如

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

然后简单地在 tbody 标签中使用它,ala &lt;tbody table-rows&gt;&lt;/tbody&gt;

【讨论】:

    【解决方案2】:
    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);
          }
        }
    

    【讨论】:

    • 您提供解决方案很好,但您的答案应始终包含一些解释和代码。谢谢!
    • 虽然欢迎使用此代码 sn-p,并且可能会提供一些帮助,但它会是 greatly improved if it included an explanation of 如何解决这个问题。没有这个,你的回答就没有多少教育价值了——记住你是在为未来的读者回答这个问题,而不仅仅是现在提问的人!请edit您的答案添加解释,并说明适用的限制和假设。
    猜你喜欢
    • 2018-10-12
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 2016-10-09
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多