En caso que tengan que usar el tipo “any”, les recomiendo usar “unknown” en su lugar. De esta forma typescript entiende que nunca va a ser un valor “undefined” o “null”.
Conoce la importancia de los formularios para tu sitio web
Versiones de Angular Forms
¿Por qué aprender Angular Forms?
Presentación del proyecto: tour por los formularios de Platzi Store
Novedades de Angular 10: cómo migrar proyectos de Angular 8 o 9 a la versión 10
Primeros pasos con Angular Forms
Template Forms vs. Reactive Forms
Dominando el FormControl y sus estados
Cómo usar inputs de texto y la importancia del type
Manejo y binding de selects y selects múltiples
Manejo y binding de inputs radio y checkbox
Aplica validaciones a un FormControl
Integración y validaciones con CSS para mostrar errores
Descubre todas las validaciones de Angular Forms
Usando FormGroup para agrupar multiples campos
Reactive Forms con FormBuilder
Los 11 validadores de Angular (y expresiones regulares)
Manejando múltiples FormsGroups
Usando componentes de Angular Material
Errores comunes de usabilidad en formularios
Validaciones personalizadas: mejorando nuestro formulario de registro
Implemeta validaciones avanzadas en PlatziStore
Cómo hacer validaciones grupales en Angular Forms
Validaciones condicionadas y reactividad a variaciones en la UI
Proyecto: formulario para crear categorías de productos
Proyecto: conectando nuestro formulario y la API
Proyecto: subir imágenes a Firebase Storage
Validaciones asincrónicas
PatchValue: crear vs. editar
Proyecto: creando el método de editar categorías
Construye formularios dinámicos conectando una API
Smart vs. dumb components: un patrón para dividir responsabilidades
Implementando smart y dumb components en PlatziStore
Proyecto: mejorando nuestro formulario de productos
Select dinámico: carga opciones desde una API
Select dinámico: trabajando con objetos
¿Cómo crear campos on demand? Forms dinámicos con FormArray
Estrategias avanzadas y optimización de formularios
Crea tu propia librería de componentes con CVA o Control Value Accesor
Crea un buscador de gifs usando la API de Giphy
Optimiza un input de búsquedas con RxJS y debounce
Examina la accesibilidad de tus formularios
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
Asynchronous validations are key to offer a smooth and optimized user experience. Imagine filling out a long form, getting to the end to save the information and surprise! an error appears. This can be frustrating, right? By using asynchronous validations, we can alert the user immediately if the name is already in use, similar to when you create an email on platforms like Hotmail. We will explore the use of an API that checks the availability of categories in real time as the user enters the information.
To perform asynchronous validation, we will use a specific endpoint of our API that checks the availability of a category.
API categories availability
(true
) or not(false
).This is the first step to connect our asynchronous validation with the frontend.
First, we must implement a method in our categories service
that connects to the availability endpoint. Here's how to do it:
function checkCategory(name) { return this.http.post('categories/availability', { name });}
This method sends the category name to the endpoint and waits for the availability response. We can specify in the code that we expect a boolean as response.
Inside our customvalidators
class, we write the asynchronous validation logic. Here we use the power of creating functions within functions, a common practice in languages like JavaScript.
import { map } from 'rxjs/operators';
static validateCategory(service) { return (control) => { const value = control.value; return service.checkCategory(value).pipe( map(response => response.isAvailable ? null : { notAvailable: true }) ); } }}
This code snippet takes the value of the control, checks its availability using the service, and returns null if it is available or an error if it is not. It is essential that you understand how RxJS observables and operators work in order to transform the responses properly.
Once our validation is configured, it is time to integrate it with the category form:
this.categoryForm = this.formBuilder.group({ name: [ '', [Validators.required, Validators.minLength(4)], [Validators.validateCategory(this.categoryService)] ] });
We include our synchronous validations first(Validators.required
and Validators.minLength
), followed by our custom asynchronous validation.
To improve the user experience, we display error messages next to the corresponding field if there is a problem with the validation.
<div*ngIf="form.errors?.notAvailable"> This name is already given to another category.</div>
These messages provide clear and immediate feedback to the user, helping them to correct errors before continuing to complete the form.
We hope you find this approach to implementing asynchronous validations useful in improving your developments. As you gain practice, these techniques will become part of your arsenal of tools for developing dynamic and responsive interfaces. Keep learning and success in your projects!
Contributions 17
Questions 2
En caso que tengan que usar el tipo “any”, les recomiendo usar “unknown” en su lugar. De esta forma typescript entiende que nunca va a ser un valor “undefined” o “null”.
NO funciona la api
Lo que me gustaria para un futuro curso es ver mas sobre RXJS los operadores map, pipe find, reduce. O existe ya un curso de este tema ???
Adjunto evidencia 😅
Hoy 06-01-2022 las consultas a la API arrojan un error en el servidor. Gracias
Si vienes del futuro como yo donde no existe el endpoint donde deben hacerse las peticiones para validar si el nombre existe o no, hagan la petición a el método getAllCategories del archivo de servicios, y el método de los validators debería quedar de la siguiente manera:
static validateCategory(service: CategoriesService) {
return (control: AbstractControl) => {
const value = control.value;
return service.getAllCategories().pipe(
map((categories) => {
const unAvailable = categories.find((category) => category.name === value);
if (unAvailable === undefined) {
return null;
}
return { not_available: true };
})
);
};
}
Con eso digamos que el filtrado que se hace en el back lo traemos al front y listo debería funcionar.
El api esta abajo, no responde
Justo este endpoint no existe en la nueva API
Pensando en tener un mejor performance a la hora de hacer las peticiones http agregué dos operadores, sin embargo no funcionó 😦
return service.checkCategory(value)
.pipe(
debounceTime(1000),
distinctUntilChanged(),
map((response: Availability) => {
const isAvailable = response.isAvailable;
if (!isAvailable) {
return {not_available: true};
}
return null;
})
);
Muy útiles las validaciones asíncronas, sin embargo noté que cada que escribo una letra en el input se hace una petición al api que configuré
ekisdé
Exelente!! Siempre tuve la duda de como hacer este tipo de validaciones
Excelente las validaciones asíncronas
De las mejores clases de este curso, que manera de darle poder a un formulario con validaciones asincrónicas
xd
consulta si yo tengo un servicio rest, que lo que hace es consulta usuario, pero yo uso para validar si existe el usuario, pero este servicio, su respuesta tiene que llenar algunos datos del formulario.
¿Cual seria la mejor forma de hacerlo?.
Want to see more contributions, questions and answers from the community?