Angular2 table rows as component
use existing table elements as selector
The table element doesn't allow <table-line>
elements as children and the browser just removes them when it finds them. You can wrap it in a component and still use the allowed <tr>
tag. Just use "tr"
as selector.
using <template>
<template>
should be allowed as well but doesn't yet work in all browsers. Angular2 actually never adds a <template>
element to the DOM, but only processes them internally, therefore this can be used in all browsers with Angular2 as well.
Attribute selectors
Another way is to use attribute selectors
@Component({
selector: '[my-tr]',
...
})
to be used like
<tr my-tr>
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(); }
}
Here's an example using a component with an attribute selector:
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] ];
}
Output:
1 2 3
11 12 13
Of course the template in the MyTrComponent would be more involved, but you get the idea.
Old (beta.0) plunker.