0

I am wondering how can I dynamically validate a form input that loops through an array using angular 7. For example if I had a first name and last name field it would have a min characters and a required validator, in the same array I could have an age input that would have a min-max and required validators, I was thinking maybe I should put them into a switch case and send the type to a validate function but I'm not too sure how I could do that

This is the code I have to loop through the array I store the type and name of the input

/*Function to get the form*/
  getForm() {
    this.api.getForm(this.Param).subscribe(
        data  => {
          this.form = data;
          console.log(this.form);
        }
    );
  }
<div class="contents">
  <form name="form" (ngSubmit)="onSubmit()" #f="ngForm" novalidate>
    <div class="row">
      <div *ngFor="let questions of form?.results[0].fields">
        <div class="md-form">
          <div class="col-12 p-3 ml-2">
            <span class="">{{questions.name}}</span><br />
            <input mdbInput type="{{questions.type}}" />
          </div>
        </div>
      </div>
    </div>
  </form>
 </div>

I was also looking at reactive forms but I don't think it would work for what I need. Thank you in advance

2
  • I would definitely check reactive forms as they are more flexible then template driven forms. Commented Nov 11, 2019 at 17:35
  • You can achieve above thing without reactive forms. But that is not a good approach. As @robert said it is better to use reactive forms. Commented Nov 11, 2019 at 17:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.