Conoce la importancia de los formularios para tu sitio web

1

Versiones de Angular Forms

2

¿Por qué aprender Angular Forms?

3

Presentación del proyecto: tour por los formularios de Platzi Store

4

Novedades de Angular 10: cómo migrar proyectos de Angular 8 o 9 a la versión 10

Primeros pasos con Angular Forms

5

Template Forms vs. Reactive Forms

6

Dominando el FormControl y sus estados

7

Cómo usar inputs de texto y la importancia del type

8

Manejo y binding de selects y selects múltiples

9

Manejo y binding de inputs radio y checkbox

10

Aplica validaciones a un FormControl

11

Integración y validaciones con CSS para mostrar errores

Descubre todas las validaciones de Angular Forms

12

Usando FormGroup para agrupar multiples campos

13

Reactive Forms con FormBuilder

14

Los 11 validadores de Angular (y expresiones regulares)

15

Manejando múltiples FormsGroups

16

Usando componentes de Angular Material

17

Errores comunes de usabilidad en formularios

18

Validaciones personalizadas: mejorando nuestro formulario de registro

Implemeta validaciones avanzadas en PlatziStore

19

Cómo hacer validaciones grupales en Angular Forms

20

Validaciones condicionadas y reactividad a variaciones en la UI

21

Proyecto: formulario para crear categorías de productos

22

Proyecto: conectando nuestro formulario y la API

23

Proyecto: subir imágenes a Firebase Storage

24

Validaciones asincrónicas

25

PatchValue: crear vs. editar

26

Proyecto: creando el método de editar categorías

Construye formularios dinámicos conectando una API

27

Smart vs. dumb components: un patrón para dividir responsabilidades

28

Implementando smart y dumb components en PlatziStore

29

Proyecto: mejorando nuestro formulario de productos

30

Select dinámico: carga opciones desde una API

31

Select dinámico: trabajando con objetos

32

¿Cómo crear campos on demand? Forms dinámicos con FormArray

Estrategias avanzadas y optimización de formularios

33

Crea tu propia librería de componentes con CVA o Control Value Accesor

34

Crea un buscador de gifs usando la API de Giphy

35

Optimiza un input de búsquedas con RxJS y debounce

36

Examina la accesibilidad de tus formularios

37

Siguientes pasos en tu carrera de desarrollo web profesional con Angular

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:

0 Días
10 Hrs
14 Min
25 Seg

Crea tu propia librería de componentes con CVA o Control Value Accesor

33/37
Resources

How to connect custom components to the Angular Reactive Forms API?

Integrating custom components into complex formulations, such as Angular Reactive Forms, is a common challenge for any development team. Many times, developers use only native HTML components or elements from external libraries like Angular Material, but today you will learn how to create and connect your own components to the Angular Reactive Forms API. This will open doors for you to create more personalized and efficient user experiences.

How to create a custom component?

First, generate a new component in your shared module:

ng generate component Stepper

This component will be automatically added to your shared module, which centralizes the components used throughout the application. Be sure to export the new component so that it is available in other modules.

How to add basic functionality to the Stepper component?

Now let's code the basic Stepper logic. The Stepper component will have two buttons to increment and decrement a value displayed on the screen.

The basic HTML code would look something like this:

<div> <button type="button" (click)="subtract()">-</button>  <div>{{ currentValue }}</div> <button type="button" (click)="add()">+</button></div></div>.

And in TypeScript, the increment logic will be handled:

export class StepperComponent { currentValue = 5;
 add() { this.currentValue++; }
 subtract() { this.currentValue--; } }}

How to integrate Stepper with Angular reactive forms?

For this custom component to work with Reactive Forms, we must implement the ControlValueAccessor interface. This allows Angular to handle the interaction between the forms and the component. Here's how to do it:

  1. Implement the interface in your component:
import { Component, forwardRef } from '@angular/core';import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({ selector: 'app-stepper', providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => StepperComponent), multi: true }]})export class StepperComponent implements ControlValueAccessor { currentValue = 0;
 writeValue(value: any): void { if (value !== undefined) { this.currentValue = value; } } }
 registerOnChange(fn: any): void { this.onChange = fn; } }
 registerOnTouched(fn: any): void { this.onTouched = fn; }. ..} }
  1. Sets the default functions for registering actions and checks:
onChange = (_: any) => {};onTouched = () => {};
  1. Updates the add and subtract methods to notify changes.
add() { this.currentValue++; this.onChange(this.currentValue);}
subtract() { this.currentValue--; this.onChange(this.currentValue);}

How to incorporate Stepper into an Angular form.

Finally, add the Stepper component to your form using formControlName. Initialize the value as you wish in FormBuilder:

this.form = this.fb.group({ stock: [100, Validators.required]});

And in the HTML template:

<form [formGroup]="form"> <app-stepper formControlName="stock"></app-stepper></form>.

Practical considerations and tips.

  • Seamless integration: When integrating this custom component, make sure it behaves intuitively with other elements.
  • Flexibility: In addition to Reactive Forms, this component will also support Template-driven Forms automatically.
  • Extensibility: Consider creating new components for other specific needs of your application.

This process allows you to develop highly customizable and effective UI components, which is vital for creating scalable and engaging applications. Now you have the power to build a truly custom UI, taking full advantage of Angular's capabilities. Ready for the next challenge in your development career? Keep exploring and creating!

Contributions 17

Questions 2

Sort by:

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

Mediante NG_VALUE_ACCESSOR y NG_VALIDATORS también podemos crear formularios reactivos reutilizables y anidados.
Dejo un artículo bastante interesante:
https://coryrylan.com/blog/building-reusable-forms-in-angular

Es una caja negra el cómo se integra con Reactive Forms. Nunca sabremos cómo funciona, pero es una maravilla!

Me siento un idiota haciendo mi formulario reactivo con @Inputs y @Outputs ajajajja que maravilloso!!!

También funciona:

this.currentValue++;
this.currentValue–;

Esta potente esta función de angular

Métodos de ControlValueAccessor

 writeValue(obj: any): void {
      
  }
  registerOnChange(fn: any): void {
      
  }
  registerOnTouched(fn: any): void {
      
  }
  setDisabledState(isDisabled: boolean): void {
      
  }

la abreviación queadaría así:
this.currentValue += 1;

Muy valiosa esta información Control Value Accesor

La sintaxis correcta para lo que querías hacer es :
this.currentValue += 1;

writeValue(value: any): void {}
registerOnChange(fn: any): void {}
registerOnTouched(fn: any): void {}
setDisabledState(isDisabled: boolean): void {}

Acabo de hacer una implementacion de CVA en el trabajo y al fin logro entenderlo del todo y comprender bien el funcionamiento. Incluso noto que tambien puede ser util utilizarlo en conjunto a input y outputs pero no para manejar el valor si no para notificar los cambios de cada boton y poder realizar funcionalidad en cada caso

Una chulada, lo integré con editor y asi puedo utilizar mi componente en varias vistas.

Super clase. gracias

Wow este curso está super bueno

Esto definitivamente es lo que más me gusta de los formularios reativos y estos últimos es lo que más me gusta de Angular

Buffffff parece magia, me pregunto si por ejemplo esto funcionaría con componentes externos que tengan ReactiveForms tambíen?

consulta, si yo en ves de asociarlo a formControlName y le pongo un ngmodel esto funcionaria igual ?