📊 Capítulo 07: Ciclo de Vida & afterRender
Especialização em Frontend com Angular
🗺️ O Ciclo de Vida Moderno do Componente
flowchart TD
CONSTRUCTOR["constructor() (Injeção de dependências e registro de effects)"]
--> NGINIT["ngOnInit() (Inicialização de chamadas assíncronas / Dados iniciais)"]
--> RENDER["Renderização do Template HTML no DOM"]
--> AFTER_NEXT["afterNextRender(() => { ... }) (Executa UMA ÚNICA VEZ após primeiro desenho)"]
--> AFTER_RENDER["afterRender(() => { ... }) (Executa após CADA ciclo de pintura no navegador)"]
--> DESTROY["DestroyRef.onDestroy() / ngOnDestroy() (Limpeza de timers e listeners)"]
style CONSTRUCTOR fill:#ede7f6,stroke:#512da8,stroke-width:2px
style NGINIT fill:#fff3e0,stroke:#ff9800,stroke-width:2px
style RENDER fill:#e1f5fe,stroke:#03a9f4,stroke-width:1.5px
style AFTER_NEXT fill:#e8f5e9,stroke:#4caf50,stroke-width:2px
style AFTER_RENDER fill:#c8e6c9,stroke:#2e7d32,stroke-width:1.5px
style DESTROY fill:#ffebee,stroke:#d32f2f,stroke-width:2px
🎯 Slide 1: afterRender e afterNextRender
-
Substituem
ngAfterViewInitpara manipulação segura de bibliotecas terceiras de DOM (gráficos Chart.js, mapas Leaflet). - Compatibilidade SSR: Essas funções NUNCA são executadas no servidor (Node.js), evitando crashes de
document is not defineddurante Server-Side Rendering!
🎯 Slide 2: Limpeza com DestroyRef
export class MonitorComponent {
constructor(destroyRef: DestroyRef) {
const timer = setInterval(() => console.log('Ping'), 1000);
destroyRef.onDestroy(() => clearInterval(timer));
}
}
- Não precisa mais implementar
implements OnDestroymanualmente!
🎯 Slide 3: takeUntilDestroyed()
- Operador RxJS nativo que cancela a inscrição do Observable automaticamente quando o componente for destruído!
Slide 1 de 1
Atalhos: ← → Navegar • Espaço Avançar • F Tela Cheia • Home Início • End Fim