我構建了以下 stackblitz 示例
https://stackblitz.com/edit/angular-y454qb?file=src/app/table-header/table-header.component.css
如您所見,我有一個父表table,其中有一個子組件稱為table-header
如果我直接在我的table組件中撰寫此代碼,那么我的th colspan屬性將被應用并獲得表格的整個寬度
<thead>
<th class="tableHeader" colspan="12">my table header</th>
</thead>
但是如果我將相同的代碼放在嵌套組件中 - 就我而言table-header
那么代碼不起作用并且 colspan 屬性不會應用于表格并且不會獲得表格的全寬。
我怎樣才能解決這個問題 ?
uj5u.com熱心網友回復:
問題是app-table-header組件是如何被 Angular 渲染的。如果您查看正在呈現的表格的結果,您將看到類似...的內容。
原始表格渲染的結果
<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>
當app-table-header渲染的存在之間一個額外的元素<table>和<thead>它打破了表。
一個可能的解決方案是制作app-table-header一個屬性選擇器,[app-table-header]并thead在您的表中使用帶有屬性選擇器的 a <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 = '';
}
表頭.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>
這將導致以下 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>
請參閱下面的堆疊閃電戰
https://stackblitz.com/edit/angular-bojuuf
編輯
- 將選擇器更新
thead[app-table-header]為@ Mazedul Islam 的建議。 - Added
@Input()to show you can pass values down with inputs. - Updated stackblitz
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/344975.html
