I built the following stackblitz example
https://stackblitz.com/edit/angular-y454qb?file=src/app/table-header/table-header.component.css
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?
CodePudding user response:
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