Angular Form customizable field

I'm trying to figure out how to create an angular form with a dynamic step. Currently, my form in TypeScript looks like this:

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
    ])
});

Let's say that the "role" FromControl (the first one) allows for 2 different values (x and y). How can I add a new field to my form that changes based on the selected role?

I was thinking of having buttons to select the role and then show the dynamic field at the bottom of the form. Depending on the role, I want to display it either as a dropdown or a chip component (both from Angular Material).

I don't think using two separate forms with big "ngIf" blocks is a good idea, as the user might start typing before changing their role between x and y.

Would creating a second form for the dynamic field be a better approach?

Appreciate any advice! Kev.

Answer №1

Avoid creating a separate form; instead, use *ngIf on your inputs to check user roles.

Follow these steps:

  1. Define a role variable in your component.ts file.
  2. Update the role variable value whenever the user role changes.
  3. Include various types of inputs in your current form.
  4. Apply *ngIf on role-specific inputs like
    <select *ngIf="role == 'ADMIN'> ... </select>
  5. Add all role-dependent inputs in a single form and follow step 4 for each input.

Additional Information: To update a specific validator when the role changes, use this method after updating the role:

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

Note: This will replace any previous validators that were added.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

``Error Message: TypeORM - could not establish database connection

I encountered an issue while running my project built with Typescript, Typeorm, and Express. The error message received when running the dev script was: connectionNotFoundError: Connection "default" was not found The content of my ormconfig.json ...

Is there a way to reset the selected value of a specific option in Mat-Select?

Using mat-select, I need to reset the selection for a specific value of mat-select's mat-option. For instance, take a look at this example on StackBlitz In the example, the mat-select has three options; when selecting Canada, it should revert back t ...

Error: setPosition function only accepts values of type LatLng or LatLngLiteral. The property 'lat' must be a numerical value in agm-core agm-overlay

Currently, I am utilizing Angular Maps powered by Google @agm-core and agm-overlay to implement custom markers. However, when using the (boundsChange) function on the agm-map component, an error occurs with the message "invalidValueError: setPosition: not ...

What is the procedure for sending a secondary route parameter to the angular 2 services module?

I'm a beginner with Angular 2 and I'm seeking advice on how to pass multiple parameters to Angular's service module. For instance, here is the first parameter I'm passing to the service through the router link. In the home-component.ht ...

Move the cursor to the end of the text when the key is released

I've developed a feature similar to that of a command line interface. When you input commands and hit the up key, the previous command is displayed. Everything is functioning as intended, but there's one minor issue. The current problem I'm ...

Issue with Navigation in Nativescript Angular: Module not found within app://

I’m facing a challenge while trying to switch to a new screen with tab navigation (within a new module) after logging in successfully. The error message that’s popping up is: “Failed to find module: “./start/start.module”, relative to app:// It ...

Oops! It appears that there is an issue with the 'value' property in Vue3

I encountered an issue while trying to reference a state variable through the store mechanism import { AppState } from '@/types' import { localStorage } from '@/utils/storage'; import { defineStore } from 'pinia'; import { get ...

Automate the process of triggering the "Organize Imports" command on a VSCode / Typescript project through code

Is there a way to automatically run VSCode's 'Organize Imports' quickfix on every file in a project, similar to how tslint can be run programatically over the entire project? tslint --project tsconfig.json --config tslint.json --fix I want ...

Angular 6 is throwing an error message stating that it cannot access the 'image' property of an undefined object

Having trouble retrieving the details, as it is rendering to the dom with an undefined error. Check out this image for reference: Welcome to the Book Details Component export class BookDetailsComponent implements OnInit { book: Book; books: Book[]; ...

Creating a fresh ngx-translate pipeline (comparing pure and impure methods)

Edit: I am looking to enhance the functionality of ngx-translate's pipe by extending it. Here is an example of how I achieved this: import { Pipe, PipeTransform } from '@angular/core'; import { TranslatePipe } from "@ngx-translate/core"; @ ...

Tips for displaying backend error messages on the frontend

I am facing an issue with returning error messages from the backend to the frontend in my Angular project. The specific requirement is to display an error message when the value of msisdn is not eligible for renewal. Currently, the hardcoded error message ...

Passing arguments from nodes in Angular 2

I am looking to pass a parameter from a node, rather than a property. Here is an example of what I want: <!-- I want to use this: --> <navbar-comp> <items> <item label="Page 1" path="/page1" /> <item label="Page 2" pat ...

Designing a Test Specification for the @Input feature in Angular 2

@Input() public set isRunning(value: boolean) { if (!value) { this.cancelTimeout(); this.isDelayedRunning = false; return; } if (this.currentTimeout) { return; } ...

Creating a functional component in React using TypeScript with an explicit function return type

const App: FC = () => { const addItem = () => { useState([...items, {id:1,name:'something']) } return <div>hello</div> } The linter is showing an error in my App.tsx file. warning There is a missing return type ...

Implementing canActivate guard across all routes: A step-by-step guide

I currently have an Angular2 active guard in place to handle redirection to the login page if the user is not logged in: import { Injectable } from "@angular/core"; import { CanActivate , ActivatedRouteSnapshot, RouterStateSnapshot, Router} from ...

Utilize Array.push to add 2 new rows to a table using Angular 4

I have two arrays that are almost identical, except for two items which are the fakeDates: this.prodotti.push({ idAgreement: this.idAgreement,landingStatus: this.landingStatus, landingType: this.landingType, startDate: this.startDate, expirationDate: thi ...

What is the appropriate method to utilize the scrollable feature in Tab View?

Currently, I am incorporating p-tabview and trying to enable the scrollable property as indicated on the primeng website: https://www.primefaces.org/primeng/showcase/#/tabview However, an error is showing up that says Can't bind to 'scrollable&a ...

Tips for retrieving data from Angular Material Table source

It's great to see everyone doing well! I'm facing an issue with rendering data to a material table, and I can't figure out why it's not working. When I try to assign the data to the table's datasource for rendering, the information ...

Utilizing backbone-forms in Typescript: A beginner's guide

Currently in my project, I utilize backbone.js along with typescript. My goal is to incorporate backbone-forms for form creation, however I am unable to locate a typescript definition file (d.ts) for this specific backbone plugin. Despite my attempts to cr ...

Completing a fetch promise and sending the outcome to a function that is not awaited

I have a function that retrieves data from a Postgresql database and returns it. The expected behavior is to fetch the data using the async function getCat(), process it in const Catalogue, and then return it to a ReactJS component. catalogue.tsx: import ...