Remove host component tag from html in angular 4

2020-01-28 08:36发布

问题:

I have a table in which I want to display a table row, which is a component. And also I want to pass data to that component:

<table>
    <th>
        <td>col 1</td>
        <td>col 2</td>
        <td>col 3</td>
    </th>
    <tr>
        <my-component [data1]="data1" [data2]="data2"></my-component>
    </tr>
    <tr *ngFor="let item of list">
        {{item}}
    </tr>
</table>

In my-component, the HTML is a few <td></td> with data rendered from data1 and data2.

But after rendering it, because of <my-component></my-component> my CSS is breaking resulting in all my-component HTML (whole table row) displaying in 1st column.

Result of above:

<table>
    <th>
        <td>col 1</td>
        <td>col 2</td>
        <td>col 3</td>
    </th>
    <tr>
        <my-component>
            <td>data1.prop1</td>
            <td>data1.prop2</td>
        </my-component>
    </tr>
    <tr *ngFor="let item of list">
        {{item}}
    </tr>
</table>

I tried the following:

@Component({
    selector: '[my-component]',
    templateUrl: 'my-component.html'
})

<tr my-component [data1]="data1" [data2]="data2"></tr>

But this results in error Can't bind to 'data1' since it isn't a known property of 'tr'.

Also I can not use @Directive as I want to render HTML.

How can I render template of <my-component></my-component> without <my-component></my-component> tag?

Other answers are of previous versions of angular. I am using Angular 4.3.4.

Any help would be appreciated..!

回答1:

you need to include tr as well in selector like below,

@Component({
 selector: 'tr[my-component]',
 template: `
   <td>{{data1.prop1}}</td>
   <td>{{data1.prop2}}</td>
   <td>{{data2.prop1}}</td>
 `
})
export class MyComponent {
  @Input() data1;
  @Input() data2;
}

Check this Plunker!!

Hope this helps!!