I have a very complex component that has a lot of **@Input()**s. For the sake of readability I would like to group the input like DexExtreme's grids do.
DevExtreme grids have a lot of Inputs and they have divided them like this:
<dx-data-grid
[dataSource]="dataSource"
[remoteOperations]="false">
<dxo-paging [pageSize]="10"></dxo-paging>
</dx-data-grid>
As you can see the paging arguments are not passed directly to dx-data-grid
but throught
a child component dxo-paging
.
I think this is a very good approach when you have very configurable components.
Anyone knows how to achieve the same result?
Thanks a lot
CodePudding user response:
It's not really about grouping Inputs but combining components. The key feature which is being used here is called content projection in Angular. It allowes you to fill predefined slots in the parent component with other components, which are passed from the outside.
The example you provided would have following structure. We would have two components: the parent DxDataGridComponent
and the child DxoPagingComponent
. You can define the inputs on both of them as you wish. Then the parent component needs to have a <ng-content>
slot, where the child component will be projected to.
Additionally you can grab a reference to this child component in your parent component by using @ContentChild
.
@Component({
selector: 'dxo-paging',
template: `
<!-- Paging stuff -->
`
})
export class DxoPagingComponent {
@Input() pageSize;
}
@Component({
selector: 'dx-data-grid',
template: `
<!-- DataGrid stuff -->
<table>
</table>
<ng-content></ng-content>
`
})
export class DxDataGridComponent implements AfterContentInit {
@Input() dataSource;
@Input() remoteOperations;
@ContentChild(DxoPagingComponent)
pagingComp: DxoPagingComponent;
ngAfterContentInit() {
console.log('Content initialized', this.pagingComp.pageSize);
}
}