When working with components in Angular we might need to load a child component in a parent component. Here’s how to go about it:
In the parent component we need to import ViewChild
from the Angular core package and then proceed to use it to load our child component:
Parent Component
parent.component.ts
import { Component, ViewChild } from '@angular/core';
import ChildComponent from '../../childComponent/child.component';
@Component({
selector: 'app-parent-component',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss'],
})
export class ParentComponent {
@ViewChild(ChildComponent) childComponent: ChildComponent
}
We then proceed to add the reference to the child component using the child component’s selector in the parent component’s view (parent.component.html
):
<ng-template>
<app-child></app-child>
</ng-template>