This Article helps to understand the concept of Content Projection in Angular using ContentChild, ContentChildren (ng-content)- Access Html Element
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.
ContentChild - Html Element
Parent Container - Level 1
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-cards',
templateUrl: './cards.component.html',
styleUrls: ['./cards.component.sass']
})
export class CardsComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
<app-carddetail>
<div #header ngProjectAs="header">Card Headerdiv>
<span id="card-sub-header">Card Sub Headerspan>
<div class="card-body">This is a card Body!!!div>
<footer title="card-footer">Card Footer.footer>
app-carddetail>
Child Container - Content binding
import { AfterContentInit, Component, ContentChild,
ElementRef, Input } from '@angular/core';
@Component({
selector: 'app-carddetail',
templateUrl: './carddetail.component.html',
styleUrls: ['./carddetail.component.sass']
})
export class CarddetailComponent implements AfterContentInit {
//Content Child
@ContentChild('header')cardHeaderData: ElementRef = {nativeElement: undefined};
constructor() { }
ngOnInit() {
}
ngAfterContentInit(): void {
this.cardHeaderData.nativeElement.style.color = 'white';
this.cardHeaderData.nativeElement.style.backgroundColor = 'black';
this.cardHeaderData.nativeElement.style.fontSize = '24px';
// debugger;
}
}
<!-- HTML -->
<ng-content select='header'></ng-content>
<ng-content select='#card-sub-header'></ng-content>
<ng-content select='.card-body'></ng-content>
<ng-content select='[title]'></ng-content>