Angular Lifecycle Hooks Part 5 - ngAfterContentChecked
HTML-код
- Опубликовано: 16 сен 2024
- What is ngAfterContentChecked?
How does it work with a sample example of the ngAfterContentChecked method?
What are lifecycle hooks?
How do they work with a sample example of the ngAfterContentChecked method?
Before learn this topic go through angular tutorial for setup and basic concepts with example click below link
• Angular Introduction ...
"Version of Angular 17" Link • Angular 17
#angularlifehooks #angular #virutchamtechs #ngaftercontentinit #ngaftercontentchecked
Try below code
//a component html
ngAfterContentChecked Example
I am A.
BComponent Content DOM
//b Component html
I am b
I am B.
Click
//bcompoennt.ts
import { Component , AfterContentChecked,AfterContentInit,ContentChild,Renderer2,ElementRef,OnInit,viewChild,AfterViewInit, ViewChild } from '@angular/core';
import { CComponent } from '../c/c.component';
@Component({
selector: 'app-b',
standalone: true,
imports: [CComponent],
templateUrl: './b.component.html',
styleUrl: './b.component.css'
})
export class BComponent implements AfterContentChecked,AfterContentInit,OnInit,AfterViewInit {
@ContentChild("BHeader",{read:ElementRef}) hRef:ElementRef |undefined
@ViewChild(CComponent,{read:ElementRef}) cRef:ElementRef |undefined
constructor(private renderer:Renderer2)
{
console.log("constructor")
}
ngAfterViewInit(): void {
console.log("ngafterviewinit")
this.renderer.setStyle(this.cRef?.nativeElement.children.item(0),'background-color',this.randomRGB())
this.renderer.setStyle(this.cRef?.nativeElement.children.item(1),'background-color',this.randomRGB())
}
ngOnInit(): void {
console.log("ngInit",this.hRef)
}
ngAfterContentChecked(): void {
console.log("ngaftercontentchecked",this.hRef)
this.renderer.setStyle(this.hRef?.nativeElement,'background-color',this.randomRGB())
}
ngAfterContentInit(): void {
console.log("ngAfterContentInit",this.hRef)
}
randomRGB(): string {
return `rgb(${Math.floor(Math.random() * 256)},
${Math.floor(Math.random() * 256)},
${Math.floor(Math.random() * 256)})`;
}
}
//c compoent.html
I am c
Hello wordld
Okay mam I'll try
Thank you for sharing mam ☺️☺️
Why using 3 components mam
Just for understanding, I made this so you can make it into a single component. When it comes to the project, it may work out like this, so I thought of it in this way.