Let’s first define the model that our component works with.
export interface TreeItem {
children?: TreeItem[];
expanded?: boolean;
}
Next, lets define our component
import {
Component,
ContentChild,
EventEmitter,
Input,
OnInit,
Output,
TemplateRef,
} from '@angular/core';
import { TreeItem } from '../tree-item';
@Component({
selector: 'ngxt-treecontrol',
templateUrl: './ngxt-treecontrol.component.html',
styleUrls: ['./ngxt-treecontrol.component.scss'],
})
export class NgxtTreecontrolComponent<T extends TreeItem> implements OnInit {
constructor() {}
ngOnInit(): void {}
@Input()
public treeData: T[] = [];
@ContentChild(TemplateRef)
public nodeTemplate: TemplateRef<any> | null = null;
ngAfterContentInit(): void {
if (!this.nodeTemplate) {
throw new Error('This component needs ng-template for the tree node.');
}
}
}
As seen above, we are using generics in TypeScript to define that our component works with any data structure that extends TreeItem
interface.
It also expects that we project in an TemplateRef
. That is nothing but ng-template
in our html.
#javascript #programming #angular