Remove host component tag from html in angular 4

对着背影说爱祢 提交于 2019-12-17 09:49:09

问题


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!!



来源:https://stackoverflow.com/questions/46671235/remove-host-component-tag-from-html-in-angular-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!