Angular2 table row as component

I am experimenting with angular2 2.0.0-beta.0

I have a table and the contents of the row are created by angular2 as follows:

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

Now this works, and I want to encapsulate the contents in a table-line component.

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

And in the component, the template has the content <tr> <td>.

But now the table no longer works. This means that the content is no longer displayed in columns. In the browser, the inspector shows me that the DOM elements look like this:

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

How can I do this job?

+57
angular
Jan 01 '15 at 12:51 on
source share
3 answers

use existing table elements as a selector

The table element does not allow <table-line> elements as children, and the browser simply removes them when it finds them. You can wrap it in a component and still use a valid <tr> . Just use "tr" as a selector.

using <template>

<template> should also be allowed, but so far does not work in all browsers. Angular2 never actually adds a <template> element to the DOM, but only handles them internally, so it can be used in all browsers with Angular2.

Attribute selectors

Another way is to use attribute selectors

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

to be used as

 <tr my-tr> 
+59
Jan 01 '15 at 13:21
source share
— -

Here is an example of 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 MyTrComponent will be more active, but you get this idea.

Old (beta.0) plunker .

+17
Jan 01 '15 at 17:14
source share

I found the example very useful, but it did not work in the 2,2,3 build, so after repeated scratching it worked again with minor 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(); } } 
+13
Dec 22 '16 at 16:04
source share



All Articles