【发布时间】:2021-03-28 23:08:13
【问题描述】:
我已经创建了通用组件,它将以表格格式呈现数据。
data-table.component.ts(这是可复用的组件,任何子组件都可以使用)
@Component({
selector: 'data-table',
templateUrl: './data-table.component.html',
styleUrls: ['./data-table.component.css']
})
export class DataTableComponent implements OnInit {
constructor() { }
ngOnInit(): void {
//wanted to access child here(or inside any method in this class) to set the width of each <td> from child
//wanted to access #rowTemplate children from child for all 3 <td>
}
setColumnWidth(width: string = "") {
if (width != "") {
return 'width:' + width;
}
}
}
data-table.component.html
<table style="width:100%;">
<thead>
<tr>
<th *ngFor="let c of columns" style="{{setColumnWidth(c.width)}}">
{{c.fieldTitle}}
</th>
</tr>
</thead>
<tbody>
<ng-container *ngTemplateOutlet="rowTemplate"></ng-container>
</tbody>
</table>
resource-updates.component.ts(这是子组件)
@Component({
selector: 'resource-updates',
templateUrl: './resource-updates.component.html',
styleUrls: ['./resource-updates.component.css']
})
export class ResourceUpdatesComponent implements OnInit {
columns: Column[] = [];
rows: any[] = [];
constructor() { }
ngOnInit(): void {
//Preparing list for columns
this.columns.push(new Column({ fieldName: 'Id', fieldTitle: 'Id', isSortable: false, width: '5%' }));
this.columns.push(new Column({ fieldName: 'Title', fieldTitle: 'Title', width: '60%' }));
this.columns.push(new Column({ fieldName: 'Type', fieldTitle: 'Type', width: '35%' }));
//Preparing list for rows
this.rows = [
{"id":5,"title":"Air Gas Guideline","type":"PPT"},
{"id":6,"title":"Air Pollution User Reference","type":"Website"},
{"id":18,"title":"Avian Influenza (H7N9) User Reference","type":"Website"},
{"id":12,"title":"Avian Influenza (H7N9) for high risk","type":"PPT"},
{"id":11,"title":"Avian Influenza (H7N9) for normal","type":"PPT"}
];
}
}
resource-updates.component.html(想在下面的 Parent(公共组件)中从 columns.width 属性设置宽度)
<ng-template #rowTemplate>
<tr *ngFor="let r of rows">
<td>{{r.id}}</td>
<td>{{r.title}}</td>
<td>{{r.type}}</td>
</tr>
</ng-template>
<data-table [columns]="columns" [rowTemplate]="rowTemplate"></data-table>
任何机构都可以帮助访问 #rowTemplate 子元素以分别从 columns[0].width 和...
【问题讨论】:
标签: angular datatable parent-child custom-component code-reuse