0

I am wondering how to make an angular form with a dynamic step. I have the following form (TS) :

this.registerForm = new FormGroup({
   role: new FormControl('', [
      Validators.required,
   ]),
   firstName: new FormControl('', [
      Validators.required,
      Validators.minLength(2),
      Validators.maxLength(20),
   ]),
   lastName: new FormControl('', [
      Validators.required,
      Validators.minLength(2),
      Validators.maxLength(20),
    ]),
    email: new FormControl('', [
       Validators.required,
       Validators.email
    ])
});

Now let's admit that my "role" FromControl (the first one) allows 2 different values (x and y), how should I proceed to have a new field in my form that is changing in function of the role form control ?

I planned to have buttons allowing to select your role and then have my dynamic field at the bottom of the form. And in one case I want to display it with a dropdown and in an other I want to display it with a chip component (both from angular material)

I can't make juste two big "ngIf" blocks containing two differents forms, cause the user may start typing and then changing his or her role from x to y and vice versa.

Would making a second from for that dynamic field be a good idea ?

Many thanks ! Kev.

Kevin Heirich
  • 109
  • 2
  • 12

1 Answers1

1

No, you should not create separate form, instead you can simply add *ngIf on your inputs which checks user role.

Here are steps you can do :

  1. Create a role variable in your component.ts file.
  2. OnChange of user role value, update role variable value to which user selected.
  3. Add different types of inputs in your existing form.
  4. Add *ngIf on your role specific inputs like <select *ngIf="role == 'ADMIN'> ... </select>
  5. You can add all inputs which varies based on role in single form, you just need add step 4 in these inputs.

Updates: Incase you want to update specific validator on change of role, you can do that like this once you update role:

this.registerForm.controls["firstName"].setValidators([Validators.minLength(1), Validators.maxLength(30)]);

Note: It will remove all previous validator added.

Naresh J
  • 2,087
  • 5
  • 26
  • 39
  • Hey there, thx for your answer ! Well my question is how will this work on the TS side ? I may not have the same validators in function of the role because the type of input is different. I feel like I should make two different form control in the form group for that dynamic field (for the two different case of role selected), and then programmaticly read values from the good one when the onsubmit button is clicked, what do you think ? – Kevin Heirich Mar 07 '21 at 13:45
  • You can dynamically change validators. Updated in answer. See this https://stackoverflow.com/questions/38797414/in-angular-how-to-add-validator-to-formcontrol-after-control-is-created – Naresh J Mar 07 '21 at 14:03
  • Glad, it helped you. – Naresh J Mar 07 '21 at 14:05