I came across some code in which some components have access to their parent component instance but I could not figure out how the "injection" takes place.
I expected the code to fit in one of those scenarios, but there is no dedicated attribute binding, nor @Injectable
decorator in the parent component, nor @Host
in children component constructor. Then, how Angular can know it has to inject the parent component instance as the first argument in children components constructor? Is this because parent and child components belong to the same module ? Is there any implicit behavior taking place here ?
Relevant code fragments
Children components receiving the parent instance inherit from an common abstract class
(This class has nothing to do with angular components)
// The "parent" component file
import {GraphComponent} from "./graph.component";
export abstract class GraphElement implements OnDestroy {
graph: GraphComponent;
constructor(graph: GraphComponent, element: ElementRef) {
this.graph = graph;
// misc instructions …
}
…
}
Children have similar @component decorator and constructor :
@Component({
selector: 'g[lines]',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `` // Empty string (not truncated), by the way why not using a directive instead?
})
export class LineComponent extends GraphElement {
constructor(graph: GraphComponent, element: ElementRef) {
super(graph, element);
console.log(graph) // Does output the "parent" graph component instance to the console
}
"Parent" component declaration:
@Component({
selector: 'graph',
styleUrls: ['./graph.component.scss'],
providers: [MiscService],
// Truncated template
template: `
<svg>
…
<svg:g>
// The only input is pure d3Js chart data
<svg:g *ngIf="linesData" [lines]="linesData" />
</svg:g>
…
</svg>
`
})
export class GraphComponent implements AfterViewInit, OnDestroy {
constructor(public elementRef: ElementRef, changeDetectorRef: ChangeDetectorRef /*, misc unrelated services */) {
this.element = elementRef.nativeElement;
// …
}
…
}