How to use @ContentChildren in Angular

 



Content Children

ContentChildren is a parameter decorator that is used to get the QueryList of elements or directives from the content DOM. The QueryList is updated whenever the child element/component is added or removed.

The child element reference is set in QueryList just before the ngAfterContentInit lifecycle Hook method.

Let's take one example to understand better about Content Children

 

Step 1: Create a project using command ng new Content-children-Example

Step 2:  Add 2 more component using ng g c component-name

Step 3: Place the below code in child.component.html

 <h1>This is child Page </h1>
<h2>{{message}}</h2>
 

Step 4: Place the below code in child.component.ts

 import { Component, OnInit } 
from '@angular/core';  
@Component({   selector:
 'app-child',   
templateUrl: './child.component.html', 
styleUrls: ['./child.component.scss'] }) 
export class ChildComponent 
implements OnInit {   message: string;   
constructor() { } ngOnIt():void   
 }   public printTitle() {    
 this.message = 
'Message is :' + new Date();  
 } }  

Step 5: Open Children.component.ts and place the below code.

 
import { ChildComponent } from './../child/child.component'; import { Component, OnInit, ContentChildren, 
QueryList, AfterContentInit } 
from '@angular/core';  @Component({   
selector: 'app-children',  
 templateUrl: './children.component.html', 
styleUrls: ['./children.component.scss'] }) 
export class ChildrenComponent
 implements OnInit, AfterContentInit { 
  message = 'Children Page'; 
@ContentChildren(ChildComponent)
 contentChildren : QueryList
<childcomponent>;   constructor() { }    ngOnInit(): void {    }  
ngAfterContentInit() {   

this.contentChildren.toArray().forEach((children, index) =&gt; { 
console.log('child component counter :', ++index);       children.printTitle();     });     } }  
</childcomponent>
 

Step 6: Place below code in children.component.html

<h1>Children Page </h1>
<h2>{{message}}</h2>
<ng-content>  </ng-content> 

Step 7: Open app.component.html 

and place the below code

 
 <h1>App Component - Content Children Example</h1>
<app-children>
<app-child>   </app-child>
<app-child>   </app-child>
<app-child>   </app-child>
<app-child>   </app-child>
<app-child>   </app-child>
</app-children>             
 

Step 8: Hit ng serve  command from command line and get the result :)

Git :
 https://github.com/coremicroservices/Angular-contentChlidren

Facebook : https://www.facebook.com/coremicroservices/?modal=admin_todo_tour

Youtube :
https://youtu.be/8Nmd-6Udsi4

 

With ❤️ Happy Coding


Comments

Popular posts from this blog

How to disable table row in Angular

How to create XML file dynamically in c#.net?

How to get Array value in Angular ?