I built the following stackblitz example
As you can see I have parent table table
which has one child component called table-header
If I write this code directly in my table
component then my th
colspan
attribute will get applied
and will get the whole width of the table
<thead> <th class="tableHeader" colspan="12">my table header</th> </thead>
but if I put the same code inside nested component – in my casetable-header
then the code does not work and the colspan attribute does not get applied to the table and does not get the full width of the table.
How can I fix this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The problem is how the app-table-header
component is rendered by Angular. If you look at the result of the table being rendered you will see something like….
result of original table render
<table>
<thead>
<th class="tableHeader" colspan="12">my table header</th>
</thead>
<app-table-header>
<thead>
<th colspan="12">my table header</th>
</thead>
</app-table-header>
</table>
When app-table-header
rendered there is an extra element between the <table>
and the <thead>
which breaks the table.
A possible solution is to make app-table-header
an attribute selector, [app-table-header]
and use a thead
in your table with the attribute selector <thead app-table-header>
.
table-header.compnonent.ts
@Component({
selector: 'thead[app-table-header]',
templateUrl: './table-header.component.html',
styleUrls: ['./table-header.component.css']
})
export class TableHeaderComponent implements {
@Input()
public heading: string = '';
}
table-header.component.html
<!-- Remove the thead from here -->
<th class="tableHeader" colspan="12">{{ heading }}</th>
table.component.html
<table>
<thead>
<th class="tableHeader" colspan="12">my table header</th>
</thead>
<thead app-table-header heading="Passing heading down with @Input"></thead>
</table>
This will result in the below html
<table>
<thead>
<th class="tableHeader" colspan="12">my table header</th>
</thead>
<thead app-table-header>
<th colspan="12">Passing heading down with @Input</th>
</thead>
</table>
See stackblitz below
EDIT
- Updated the selector to
thead[app-table-header]
as suggested by @
Mazedul Islam. - Added
@Input()
to show you can pass values down with inputs. - Updated stackblitz
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0