Introducción a Angular y Fundamentos
Aprende Angular 17
Creando tu primer proyecto en Angular
Implementando estilos
Mostrando elementos
Property Binding en Angular
Event Binding: click y doble click
Event binding: keydown
Modelo de reactividad con Signals
Creando un Signal en Angular
Estructuras de control en Angular
Directivas de control
Uso de ngFor
ngFor para objetos
Update Tasks
Uso de ngIf
Uso de ngSwitch y ngSwitchDefault
Controlando un input
Manejo de formularios en Angular
Alistando tu aplicación para producción
Estilos al modo Angular
Clases en Angular
Editing mode
Estados compuestos con computed
Usando effect para localStorage
Uso de ngbuild
Despliegue con Firebase Hosting
Nueva sintaxis en Angular
Directivas @For, @switch
Migrando a la nueva sintaxis de Angular v17
Componentes Reutilizables y Comunicación
Construyendo un e-commerce en Angular
Componentes en Angular
Mostrando los componentes
Angular DevTools
Uso de Inputs en Angular
Uso de Outputs en Angular
Componentes para Producto
Ciclo de vida de los componentes
Ciclo de vida de componentes
Ciclo de vida de componentes: ngOnChanges
Ciclo de vida de componentes: ngOnInit
Detectando cambios en los inputs
Evitando memory leaks con ngDestroy
Audio player con ngAfterViewInit
Creando la página "about us" o "conócenos"
Mejorando la interfaz del producto
Creando componente de productos
Creando el Header
Creando el carrito de compras
Comunicación padre e hijo
Calculando el total con ngOnChanges
El problema del prop drilling
Reactividad con signals en servicios
Entendiendo la inyección de dependencias
Integración y Datos
Obteniendo datos una REST API
Importaciones cortas en Typescript
Pipes en Angular
Construyendo tu propio pipe
Utilizando librerías de JavaScript en Angular
Conociendo las directivas
Deployando un proyecto en Vercel
Enrutamiento y Navegación
Ruta 404
Uso del RouterLink
Vistas anidadas
Uso del RouterLinkActive
Detalle de cada producto
Obteniendo datos del producto
Galería de imagenes
Detalle de la galería
Perfeccionando tu e-commerce
Mostrando categorias desde la API
Url Params
LazyLoading y Code Splitting
Aplicando LazyLoading
Prefetching
Usando la nueva sintaxis de Angular 17
Lanzando tu aplicación a producción
You don't have access to this class
Keep learning! Join and start boosting your career
The ngOnInit
event is one of the most essential lifecycles in application development with Angular. It is often confused with the constructor, but it has a different purpose and it is crucial to understand its capabilities.
Unique use: while a constructor can run multiple times before and after rendering, ngOnInit
runs only once, immediately after the initial rendering of the component. This makes it the ideal place for component initialization tasks.
Asynchronous tasks: This event is perfect for handling asynchronous operations such as API calls or subscriptions to observables, as it ensures that the component has already been fully rendered.
To illustrate its use, if you want to fetch a list of products from a data source, ngOnInit
is the right time to do a fetch
and manipulate the response to update the component.
ngAfterViewInit
is another lifecycle that is triggered after ngOnInit
and has a specific function.
When declaring one component inside another, ngAfterViewInit
will inform you when those child components are ready. This is essential in applications that use complex or hierarchical architectures.
Finally, ngOnDestroy
is the event that is executed when a component is about to be destroyed.
To destroy a component, you can use a directive such as ngIf
, which, when a condition is not met, will remove the component and consequently trigger ngOnDestroy
.
For example, if you have a component whose visibility depends on a value such as duration
, when it becomes negative, ngOnDestroy
will be executed and remove the component. If the value subsequently changes to a positive state, the entire lifecycle of the component is restarted, starting from the constructor.
These lifecycles are critical for performance and efficient resource management in Angular applications. Knowing them will allow you to write more robust and optimized code. Keep exploring the possibilities of Angular and keep learning!
Contributions 6
Questions 2
✅
<input type="number" [value]="duration()" (change)="changeDuration($event)">
<input type="text" [value]="message()" (change)="changeMesage($event)">
@if(duration()> 0){ <app-counter [duration]="duration()" [message]="message()"></app-counter> }
``````js import { Component, Input, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-counter', standalone: true, imports: [], templateUrl: './counter.component.html', styleUrl: './counter.component.css', }) export class CounterComponent { @Input({ required: true }) duration = 0; @Input({ required: true }) message = ''; constructor() { // NO ASYNC // before render console.log('nuestro constructor'); console.log('-'.repeat(10)); } ngOnChanges(changes: SimpleChanges) { // before and during render console.log('ngOnChanges'); console.log('-'.repeat(10)); console.log(changes); } ngOnInit() { // una vez // async, then, subs console.log('ngOnInit'); console.log('-'.repeat(10)); console.log('duration =>', this.duration); console.log('message =>', this.message); console.log('-'.repeat(10)); } ngAfterViewInit() { // despues de pintar el componente padre e hijos console.log('ngAfterViewInit'); console.log('-'.repeat(10)); } ngOnDestroy() { console.log('ngOnDestroy'); console.log('-'.repeat(10)); } } ```como referencia y en .ts cree una propiedad que guarda dicho elemento. Luego extraje el contenido de esa etiqueta \
en el onInit y me dio como resultado undefined; quiere decir que no encontró al elemento \
por tanto su contenido no existe y da undefined, oséa que, onInit se activa **antes del render**. En cambio, cuando hago lo mismo en el afterInit si encuentra el contenido de la etiqueta \
, oséa, **después del render.** ```js counter.html //Esto es una pieza solamente del .ts
Counter
Soy ref de pruebaen el componente, no me presenta problema al renderizar el HTML, al dejarlo, me presenta problemas con la Hidratación en el DOM. \
: 
Want to see more contributions, questions and answers from the community?