首页 文章

Angular2表行作为组件

提问于
浏览
77

我正在尝试使用angular2 2.0.0-beta.0

我有一个表格,行内容由angular2以这种方式生成:

<table>
        <tr *ngFor="#line of data">
            .... content ....
        </tr>
    </table>

现在这个工作,我想将内容封装到一个组件“table-line” .

<table>
        <table-line *ngFor="#line of data" [data]="line">
        </table-line>
    </table>

在组件中,模板具有<tr> <td>内容 .

但是现在 table 不再有用了 . 这意味着,内容不再显示在列中 . 在浏览器中,检查器向我显示DOM元素如下所示:

<table>
        <table-line ...>
            <tbody>
                <tr> ....

我怎样才能做到这一点?

4 回答

  • 23

    use existing table elements as selector

    table元素不允许 <table-line> 元素作为子元素,浏览器只有在找到元素时才会删除它们 . 您可以将其包装在组件中,并仍然使用允许的 <tr> 标记 . 只需使用 "tr" 作为选择器 .

    using <template>

    <template> 也应该被允许,但在所有浏览器中都不起作用 . Angular2实际上从不向DOM添加 <template> 元素,但只在内部处理它们,因此这也可以在所有具有Angular2的浏览器中使用 .

    Attribute selectors

    另一种方法是使用属性选择器

    @Component({
      selector: '[my-tr]',
      ...
    })
    

    用得像

    <tr my-tr>
    
  • 80

    我发现这个例子非常有用,但它在2,2.3版本中没有用,所以经过多次头部刮擦后再次使用一些小的改动 .

    import {Component, Input} from '@angular/core'
    
    @Component({
      selector: "[my-tr]",
      template: `<td *ngFor='let item of row'>{{item}}</td>`    
    })
    export class MyTrComponent {
      @Input("line") row:any;
    }
    
    @Component({
      selector: "my-app",
      template: `<h1>{{title}}</h1>
      <table>
        <tr  *ngFor="let line of data" my-tr [line]="line"></tr>
      </table>`
    
    })
    export class AppComponent {
    
      title = "Angular 2 - tr attribute selector!";
      data = [ [1,2,3], [11, 12, 13] ];
      constructor() { console.clear(); }
    }
    
  • -2

    以下是使用带有属性选择器的组件的示例:

    import {Component, Input} from '@angular/core';
    @Component({
      selector: '[myTr]',
      template: `<td *ngFor="let item of row">{{item}}</td>`
    })
    export class MyTrComponent {
      @Input('myTr') row;
    }
    @Component({
      selector: 'my-app',
      template: `{{title}}
      <table>
        <tr *ngFor="let line of data" [myTr]="line"></tr>
      </table>
      `
    })
    export class AppComponent {
      title = "Angular 2 - tr attribute selector";
      data = [ [1,2,3], [11, 12, 13] ];
    }
    

    输出:

    1   2   3
    11  12  13
    

    当然,MyTrComponent中的模板会更复杂,但你明白了 .

    旧(beta.0)plunker .

  • 24

    试试这个

    @Component({
        selecctor: 'parent-selector',
        template: '<table><body><tra></tra></body></table>'
        styles: 'tra{ display:table-row; box-sizing:inherit; }'
    })
    export class ParentComponent{
    }
    
    @Component({
        selecctor: 'parent-selector',
        template: '<td>Name</td>Date<td></td><td>Stackoverflow</td>'
    })
    export class ChildComponent{}
    

相关问题