@ContentChild in Angular | | Data Binding | Angular 15+
content_projection:
when we include child component in parent, and add custom html between open and close tags the html is injected to child
component in place of <ng-content> tag
parent.component.html
<div class="mt-5">
<app-demo>
<p #myprogram>MY line is </p>
</app-demo>
</div>
child.component.html
<div class="alert alert-primary" #mydiv>
I am child component
<ng-content></ng-content>
</div>
from child.component.ts using @ViewChild we can access any div, p or directive using reference
export class ChildComponent {
ngAfterViewInit() {
console.log(this.pg_element);
}
@ContentChild("mydiv") pg_element!:ElementRef;
}
____________________
____________________
@ContentChild
ContentChild is a decorator in Angular that allows you to obtain the first matching element or directive from the projected content (content passed using ng-content). It is useful when you want to access or manipulate a specific child element or directive in the projected content of a component.
ContentChild provides a reference to the child element or directive and updates it whenever the content changes. You can use it in combination with the AfterContentInit and AfterContentChecked lifecycle hooks to perform custom logic when the content is initialized or updated.
we use the content child decorator to access html elements components or directives from the view template of parent component in the component class of child component. but in parent data inside child component is acess ie
parent.component.html
<div class="mt-5">
<app-demo>
<p #myprogram>tjos os laskdflks idf</p>
</app-demo>
</div>
child.component.html
<div class="alert alert-primary mt-2" role="alert">
This is a primary {{value}} it out!
<ng-content></ng-content>
</div>
child.component.ts
export class DemoComponent {
ngAfterViewInit() {
console.log(this.pg_element);
}
@ContentChild("myprogram") pg_element!:ElementRef;
}