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.
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 :
role
variable in your component.ts
file.role
variable value to which user selected.inputs
in your existing form.*ngIf
on your role specific inputs like <select *ngIf="role == 'ADMIN'> ... </select>
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.