Angular2表行作为组件

我正在用 angular22.0.0-beta.0做实验

我有一个表,行的内容是通过 angular2这样生成的:

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

现在可以工作了,我想将内容封装到一个组件“表行”中。

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

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

但是现在表不再工作了,这意味着内容不再显示在列中。 在浏览器中,检查器显示 DOM 元素如下所示:

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

我该怎么做?

69722 次浏览

使用现有的表元素作为选择器

Table 元素不允许将 <table-line>元素作为子元素,浏览器只是在找到它们时删除它们。您可以将它包装在一个组件中,同时仍然使用允许的 <tr>标记。只需使用 "tr"作为选择器。

使用 <template>

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

Attribute selectors

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

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

被当作

<tr my-tr>

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

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 中的模板会涉及更多内容,但是您已经了解了这个想法。

老(测试版。0) 混蛋

I found the example very usefull but it didn't work in the 2,2.3 build, so after much head scratching made it work again with a few small changes.

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(); }
}

试试这个

@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{}

为组件样式添加“ display: content”为我所用。

CSS:

.table-line {
display: contents;
}

HTML:

<table>
<table-line class="table-line" [data]="line">
</table-line>
</table>

为什么这样?

当实例化一个组件时,在编译之后角度会将组件的内容包装在 DOM 中,如下所示:

<table>
<table-line>
<tr></tr>
</table-line>
</table>

但是为了正确显示表,tr标记不能被任何东西包装。

因此,我们将 display: contents添加到这个新元素中。据我所知,这样做是为了告诉浏览器不应该呈现这个标记,并显示内部内容,就好像没有包装一样。因此,虽然标记仍然存在,但它不会直接影响表,而且 tr标记被视为 table标记的直接子标记。

If you'd like to investigate further on how contents works: Https://bitsofco.de/how-display-contents-works/