This Article helps to understand the concept of Content Projection in Angular using ContentChildren (ng-content)- Access Child Container
Content Projection in Angular may be performed with ContentChild and ContentChildren.
ContentChild and ContentChildren are property decorators. They are used to query or helps to get a reference to the projected content. Content received by the child component from its parent component is referred to as projected content. Conversely, a parent component utilises ViewChild or ContentChild to gain access to a child component.
ContentChildren - Access Child Container
If we have more than one ContentChild, we can access them as ContentChildren
Parent Container - Level 1
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hub',
templateUrl: './hub.component.html',
styleUrls: ['./hub.component.sass']
})
export class HubComponent implements OnInit {
notifications: any;
ngOnInit() {
this.notifications = this.listNotifications();
}
listNotifications() {
return [
'Learn Angular',
'Learn DOM Manipulation ',
'Learn ViewChild',
'Learn ViewChildren'
];
}
}
<p>Hub Worksp>
<div>
<app-notification-container>
<app-notification
*ngFor="let n of notifications"
[notification]="n"
>app-notification>
app-notification-container>
div>
Child Container - Content binding
import {
Component,
OnInit,
ContentChildren,
AfterContentInit,
QueryList,
} from "@angular/core";
import { NotificationComponent } from "../notification/notification.component";
@Component({
selector: "app-notification-container",
templateUrl: "./notification-container.component.html",
styleUrls: ["./notification-container.component.sass"],
})
export class NotificationContainerComponent implements OnInit {
notification = "Notification Container Works!";
constructor() {}
ngOnInit() {}
@ContentChildren(NotificationComponent)
MessageComponnetContentChild: QueryList<NotificationComponent>;
ngAfterContentInit() {
console.log(this.MessageComponnetContentChild);
}
}
<div>
<h3>{{notification}}h3>
<ng-content select="app-notification">ng-content>
div>
Output as: