0

Estoy iniciando un proyecto y quiero hacerlo muy sencillo, estoy creando componentes y me estoy ayudando con Angular Material. Estoy creando unos inputs basados en una interfaz, se ciclan y se arman y estos se ligan a un FormGroup cuando escribo en ellos y no tienen el formato correcto (Dado por Validators) bota el error, funciona como debe ser. El problema es cuando hago submit del form, si no escribo nada ni toco los inputs, no se validan, y creo que debería hacerlo, es decir, aunque el FormControl bindeado tenga errores no se muestran

Esta es la interfaz de los inputs

foo-input.interface.ts

export interface FooInput {
    type: string;
    label: string;
    placeholder: string;
    formControl: string;
    readonly: boolean;
    validators?: any[];
    hint?: string;
    error?: string;
    suffixIcon?: string;
    prefixIcon?: string;
}

Este es el HTML del componente

foo-input.component.html

<div [formGroup]="form">
  <mat-form-field appearance="outline">
    <mat-label>
      {{ inputData.label }}
    </mat-label>
  
    <input matInput 
      [type]="inputData.type" 
      [placeholder]="inputData.placeholder"
      [readonly]="inputData.readonly"
      [formControlName]="inputData.formControl"
    >
    <mat-icon matSuffix *ngIf="inputData.suffixIcon">
      {{ inputData.suffixIcon }}
    </mat-icon>
  
    <mat-icon matPrefix *ngIf="inputData.prefixIcon">
      {{ inputData.prefixIcon }}
    </mat-icon>
  
    <mat-hint *ngIf="inputData.hint">
      {{inputData.hint}}
    </mat-hint>
    <mat-error
      *ngIf="inputData.error"
    >
      {{ inputData.error }}
    </mat-error>
  
  </mat-form-field>
</div>

Dejo también el controlador de este HTML, no pondré los .module.ts por que todo se está importando bien ( Incluyendo ReactiveFormsModule y FormsModule )

foo-input.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FooInput } from '../../interfaces/foo-input.interface';

@Component({
  // tslint:disable-next-line: component-selector
  selector: 'foo-input',
  templateUrl: './foo-input.component.html',
  styleUrls: ['./foo-input.component.scss']
})
export class FooInputComponent implements OnInit {

  @Input() inputData: FooInput;
  @Input() form: FormGroup;

  constructor() { }

  ngOnInit(): void {}

}

Este es el HTML de cómo se están ciclando

app.component.html

<form [formGroup]="form" (submit)="submit()">
    <foo-input 
        *ngFor="let input of inputs"
        [form]="form" 
        [inputData]="input">
    </foo-input>
    <button type="submit">Enviar</button>
</form>

Y por último y no menos importante, cómo se arman dinámicamente esos inputs

app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { FooInput } from '../app/interfaces/foo-input.interface';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent implements OnInit {
  title = 'foo';
  passwordRegex = '^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$';

  inputs: FooInput[] = [
    {
      label: 'Correo electrónico',
      type: 'email',
      placeholder: 'Escribe tu correo electrónico',
      readonly: false,
      formControl: 'email',
      error: 'El correo electrónico no tiene el formato correcto',
      validators: [ Validators.required, Validators.email ]
    },
    {
      label: 'Contraseña',
      type: 'password',
      placeholder: 'Escribe tu contraseña',
      readonly: false,
      formControl: 'pass',
      error: 'La contraseña no tiene el formato correcto',
      validators: [ Validators.required, Validators.pattern( this.passwordRegex ) ]
    }
  ];

  form = new FormGroup({});

  ngOnInit(): void {
    this.inputs.forEach( (input: FooInput) => {
      this.form.addControl( input.formControl, new FormControl( null, input.validators ) );
    });
  }

  submit(): void {
    console.log( this.form );
    if ( this.form.valid ) {
      console.log( 'Valido' );
    } else {
      this.inputs.map( ( input: FooInput ) => this.form.controls[ input.formControl ].updateValueAndValidity() );
    }
  }

}

Intenté usar

form = new FormGroup({}, { updateOn: 'submit' });

Y ahora se validan al hacer submit, pero ya no hacen nada los controles cuando se hace change Intenté con 'submit | change' pero no me lo aceptó.

.updateValueAndValidity()

No hace nada

¿Cómo podría poner la validación a ambas funcionalidades, tanto change como submit?

1 respuesta 1

2

El form tiene un método llamado markAllAsTouched el cual de acuerdo a la documentación:

"Marks the control and all its descendant controls as touched. (Marca el control y todos sus controles descendientes con el estado touched) "

Al marcar todos los hijos directos cómo touched todos los errores deben mostarse, si usas el updateOn:'submit' los controles no van a disparar ningún evento hasta el momento del submit del formulario, por lo que al editar algún control la validación no funcionaría.

Modificando tu código en el submit, podrías hacer algo cómo esto:

  submit(): void {
console.log( this.form );
if ( this.form.valid ) {
  console.log( 'Valido' );
} else {
  this.form.markAllAsTouched();
}

}

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.