Angular change html tag programmatically when inheriting template

Viewed 137

I have a Component, DataGrid, which represents a table with expandable rows. Each row, when expanded, shows a child DataGrid table, which is very similar to the parent DataGrid component. Therefore I defined a base class DataGridComponent, from which the child inherits the both the component and the template. however, I need to change one of the tags in the child's template. Do I have to rewrite the entire template, or could I just point the templateUrl to the parent's template and programmatically change the one html tag that I need to change?

Minimal Example:

base.component.ts

@Component({
 selector: 'datagrid',
 templateUrl: 'datagrid.component.html'
})
export class DataGridComponent {
    childEnabled:boolean = true;
 // stuff
}

datagrid.component.html

<div>...</div>
<div *ngIf="childEnabled">
    <childgrid
     [options]="childOptions"
     >
    </childgrid>
</div>

child.component.ts

@Component({
 selector: 'childgrid',
 templateUrl: 'datagrid.component.html' // <-- POINT TO BASECLASS TEMPLATE
})
export class ChildGridComponent extends DataGridComponent{
}

childgrid.component.html // <-- HOW THE (REAL) TEMPLATE SHOULD BE

<div>...</div>
<div *ngIf="childEnabled">
    <grandchildgrid
     [options]="childOptions"
     >
    </grandchildgrid>
</div>

grandchild.component.ts

@Component({
 selector: 'grandchildgrid',
 templateUrl: 'datagrid.component.html' // <-- POINT TO BASECLASS TEMPLATE
})
export class GrandChildGridComponent extends DataGridComponent{
 constructor() {
  super();
  childEnable=false;
 }
}

grandchildgrid.component.html // <-- HOW THE (REAL) TEMPLATE SHOULD BE

<div>...</div>
<div *ngIf="childEnabled">
    <grandchildgrid
     [options]="childOptions"
     >
    </grandchildgrid>
</div>

and so on until childEnabled is set to false. Is there any chance to do something like this and is it something that would make sense from an angularly point of view? Would ng-content be of any help in this case?

1 Answers
  • The content of DataGrid can go into a separate component and that can be used as a template in both parent and child DataGrid.
  • Alternative option is to have the same tags and control behavior using different class and id for parent and child
Related