Search code examples
angulartypescriptangular-formsangular11

Angular Form dynamic field


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.


Solution

  • 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.