Introducción a Angular y Fundamentos

1

Aprende Angular 17

2

Creando tu primer proyecto en Angular

3

Implementando estilos

4

Mostrando elementos

5

Property Binding en Angular

6

Event Binding: click y doble click

7

Event binding: keydown

8

Modelo de reactividad con Signals

9

Creando un Signal en Angular

Estructuras de control en Angular

10

Directivas de control

11

Uso de ngFor

12

ngFor para objetos

13

Update Tasks

14

Uso de ngIf

15

Uso de ngSwitch y ngSwitchDefault

16

Controlando un input

17

Manejo de formularios en Angular

Alistando tu aplicación para producción

18

Estilos al modo Angular

19

Clases en Angular

20

Editing mode

21

Estados compuestos con computed

22

Usando effect para localStorage

23

Uso de ngbuild

24

Despliegue con Firebase Hosting

25

Nueva sintaxis en Angular

26

Directivas @For, @switch

27

Migrando a la nueva sintaxis de Angular v17

Componentes Reutilizables y Comunicación

28

Construyendo un e-commerce en Angular

29

Componentes en Angular

30

Mostrando los componentes

31

Angular DevTools

32

Uso de Inputs en Angular

33

Uso de Outputs en Angular

34

Componentes para Producto

Ciclo de vida de los componentes

35

Ciclo de vida de componentes

36

Ciclo de vida de componentes: ngOnChanges

37

Ciclo de vida de componentes: ngOnInit

38

Detectando cambios en los inputs

39

Evitando memory leaks con ngDestroy

40

Audio player con ngAfterViewInit

41

Creando la página "about us" o "conócenos"

Mejorando la interfaz del producto

42

Creando componente de productos

43

Creando el Header

44

Creando el carrito de compras

45

Comunicación padre e hijo

46

Calculando el total con ngOnChanges

47

El problema del prop drilling

48

Reactividad con signals en servicios

49

Entendiendo la inyección de dependencias

Integración y Datos

50

Obteniendo datos una REST API

51

Importaciones cortas en Typescript

52

Pipes en Angular

53

Construyendo tu propio pipe

54

Utilizando librerías de JavaScript en Angular

55

Conociendo las directivas

56

Deployando un proyecto en Vercel

Enrutamiento y Navegación

57

Ruta 404

58

Uso del RouterLink

59

Vistas anidadas

60

Uso del RouterLinkActive

61

Detalle de cada producto

62

Obteniendo datos del producto

63

Galería de imagenes

64

Detalle de la galería

Perfeccionando tu e-commerce

65

Mostrando categorias desde la API

66

Url Params

67

LazyLoading y Code Splitting

68

Aplicando LazyLoading

69

Prefetching

70

Usando la nueva sintaxis de Angular 17

71

Lanzando tu aplicación a producción

You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

1 Días
21 Hrs
18 Min
39 Seg

Ciclo de vida de componentes: ngOnInit

37/71
Resources

What is ngOnInit and why is it so important?

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.

How does ngAfterViewInit work?

ngAfterViewInit is another lifecycle that is triggered after ngOnInit and has a specific function.

  • Child component rendering: This event is key to determine when the child components of a parent component have been fully rendered. It is useful if you need to interact with the DOM elements of those child components.

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.

When is ngOnDestroy used?

Finally, ngOnDestroy is the event that is executed when a component is about to be destroyed.

  • Cleanup and Unsubscribe: This is normally used to free resources, cancel subscriptions and avoid memory leaks when the component is no longer required.

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

Sort by:

Want to see more contributions, questions and answers from the community?

Por alguna razón, me marcaba este error al escribir la directiva de \*ngIf `If the 'ngIf' is an Angular control flow directive, please make sure that either the 'NgIf'` Basta con agregar un import de CommonModule en archivos de about.component.ts y counter.component.ts, asi: `import { CommonModule } from '@angular/common';` y agregarlo en los imports ```js @Component({ ... imports: [CommonModule], ... }) ```

Codigo de la clase: ```js

<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)); } } ```
Para saber cuando se activa el onInit, en el counter tomé un elemento \

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 prueba
counter.ts @ViewChild('text_test') textTest!: ElementRef<HTMLElement> ngOnInit(): void { console.log('Init'); console.log("ELEMENTO", this.textTest.nativeElement.textContent); //Da error undefined console.log('-'.repeat(10)); } ngAfterViewInit(): void { console.log('Afterview'); console.log("After", this.textTest.nativeElement.textContent);//Obtenemos el contenido console.log('-'.repeat(10)); } ```Por último recordar comentar la línea del onInit donde se espera obtener el contenido de la etiqueta p para poder probar el afterInit
Esto se vuelve mas divertido cuando el proyecto en el que trabajas tiene librerías externas y tienes que interactuar con ellas
Quitandole la etiqueta \

en el componente, no me presenta problema al renderizar el HTML, al dejarlo, me presenta problemas con la Hidratación en el DOM. \

: ![](https://static.platzi.com/media/user_upload/image-3378b5f7-c074-4f0e-854f-ff58e894a401.jpg)