Search code examples
htmlangulartypescriptangular-materialformbuilder

How to add Validators, when using FormBuilder.group() with an template array in Angular?



I'm trying to build a form that input fields are defined in an array looking like this:

export const FormTemplate = [

    //contact 
    {
        name: '',
        lastname: '', //required
        email: '', //required, valid
        phone: '',     
    },

And I want to add validators to the fields 'lastname' and 'email'.
My .ts file looks like this:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { FormBuilder, FormGroup, FormArray, Validators} from '@angular/forms';
import { throwError } from 'rxjs';
import { saveAs } from 'file-saver'
import { FormTemplate } from './form-template'

@Component({
  selector: 'app-request-form',
  templateUrl: './request-form.component.html',
  styleUrls: ['./request-form.component.sass']
})
export class RequestFormComponent implements OnInit {
  formTemplate = FormTemplate;
  contactForm: FormGroup;
  
  submitData;
  url = 'http://localhost:3000/';
  
  constructor(
    private fb: FormBuilder,
    private http: HttpClient
  ) { }

  ngOnInit(): void {
   this.contactForm = this.fb.group(this.formTemplate[0],{
      validator: Validators.compose([
        Validators.email,
        Validators.required
      ])
    });
  }
  submitToServer(){
    this.submitData = [
      this.contactForm.value,
      this.addressForm.value, 
      this.companyForm.value,
    ];
    var mediaType = 'application/pdf';
      this.http.post(this.url, this.submitData, {responseType: 'blob'}).subscribe(
        (response) =>{
          var blob = new Blob([response], {type: mediaType});
          //saveAs(blob, 'name.pdf');
        },
        e => {
          alert(e.message)
          throwError(e);}
      )
  }

  get email(){
    return this.contactForm.get('email');
  }

And here is my html:

<mat-horizontal-stepper>
<mat-step>
    Value:{{contactForm.value | json}}
    <form [formGroup]="contactForm" class="contact">
        <mat-form-field>
            <input matInput placeholder="name" formControlName="name" class="input">
        </mat-form-field>
        <mat-form-field>
            <input matInput placeholder="lastname" formControlName="lastname">
        </mat-form-field>
        <mat-form-field>
            <input type="email" matInput placeholder="email" formControlName="email">
            <mat-error *ngIf="email.invalid && email.touched"> 
                Email looks wrong
            </mat-error>
        </mat-form-field>
        <mat-form-field>
            <input type="tel" matInput placeholder="phone" formControlName="phone">
        </mat-form-field>
    </form>
    <div>
        <button mat-button matStepperPrevious>Back</button>
        <button mat-button matStepperNext>Next</button>
    </div>
</mat-step> 

I want to work with an array that works as a template, because I dont want to define every input field in my .ts file. But is there no other way when I want to use validators?
Thanks in advance


Solution

  • I found a way to do get the expected result

    Thats how my template .ts looks now:

    import {Validators} from '@angular/forms';
    export const FormTemplate = [
    
    //contact 
    {
        name: '',
        lastname: ['',[
            Validators.required
        ]], 
        email: ['',[
            Validators.required,
            Validators.email
          ]],
        phone: '',       
    },
    

    And heres my component.ts file:

    ngOnInit(): void {
    this.contactForm = this.fb.group(this.formTemplate[0]);
    }