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

Set the default page for the p-table

My English proficiency is lacking. I am currently using a p-table with pagination, but I need to modify the pagination in the HTML code. <p-table #dt [columns]="cols" [value]="values" [paginator]="true" [rows]="10" (onFilter)="filtra ...

Is there an issue with loading a local image? Could it be related to Angular or Chrome

Currently, I am working on a webpage that is designed to showcase a collection of images. The API I am using returns a list of objects, each containing an imgUri property which holds the absolute path to the corresponding image stored in a shared folder. ...

Is it possible for me to tap into the component creation process within the Angular Router?

Inspiration struck me when I realized the potential of adding a directive to the component designed for this particular route. It would elevate the functionality by letting me convey crucial information in a more declarative manner. Despite learning that ...

Displaying a default input placeholder in Kendo UI Datepicker for Angular 2

I've recently implemented the [Datepicker feature from Telerik Kendo UI][1] While the datepicker functions perfectly, I have encountered a single issue where it displays undefined when the date value is not defined: [![enter image description here][ ...

Leveraging Angular 2 and RxJs 5 beta observables to continuously stream data from a while loop

I am looking to develop a straightforward Angular 2 application that calculates prime numbers within a while loop and continuously updates the view with newly discovered values. My goal is to showcase the list of prime numbers using *ngFor in real-time, gi ...

I am looking to update my table once I have closed the modal in Angular

I am facing an issue with refreshing the table in my component using the following function: this._empresaService.getAllEnterprisePaginated(1);. This function is located in my service, specifically in the modal service of the enterprise component. CODE fo ...

How can different styles be seamlessly combined when customizing Fabric components?

Imagine I am enhancing a Fabric component by adding custom styles and wishing to combine any additional styles passed in through its props. Here's the solution I've devised: const { TextField, Fabric , IButtonProps, mergeStyleSets } = window.Fab ...

Guidance on specifying a type based on an enum in Javascript

I have a list of animals in an enum that I want to use to declare specific types. For instance: enum Animals { CAT = 'cat', DOG = 'dog', } Based on this Animal enum, I wish to declare a type structure like so: type AnimalType = { ...

How to Apply a CSS Class to the Body Tag in Angular 2.x

How can I add [class.fixed]="isFixed" to the body tag when Angular 2.x is bootstrapped inside the body (outside my-app)? <html> <head> </head> <body [class.fixed]="isFixed"> <my-app>Loading...</my-app> </body> & ...

What exactly is the function of the NextPage feature in Next.js?

Recently, I began incorporating TypeScript into my Next project. Could someone clarify the purpose of the following code snippets for me? import { NextPage } from 'next'; export const Page: NextPage = () => {} After reviewing the documentation ...

Combining Spring Boot and Angular applications for seamless integration

I am trying to connect my Spring Boot application with an Angular application that are running on different servers. When attempting to access REST API from the Angular app, the API call is successful but I encounter an error response on the UI. Acc ...

Navigating to a Child Module within a Parent Module in Angular 2 Release Candidate 5

I am currently in the process of updating an application I have been working on to the latest Angular 2 release candidate. As part of this upgrade, I am utilizing the NgModule spec and transitioning all parts of my application into modules. So far, the tra ...

Hiding the line connector between data points in ChartJs

I recently took over a project that includes a line chart created using Chart.js by the previous developer. My client has requested that I do not display a line between the last two data points. Is this possible with Chart.js? I have looked through the doc ...

The element 'commit' cannot be found within the property

I am facing an issue when transitioning from using Vuex in JavaScript to TypeScript. The error message Property 'commit' does not exist appears in Vuex's mutations: const mutations = { methodA (): none { this.commit('methodB' ...

The PassportJS logged in feature always yields a result of zero

After successfully implementing passportJS in my application, I encountered an issue with the current connected user. When using (req.isAuthenticated()), it always returns "0". Here is the code snippet from auth.js: /* Passport - Sessions - Cookies D ...

Unusual output from the new Date() function: it displays the upcoming month

Your assistance and explanation are greatly appreciated. I have created a method that is supposed to return all the days of a given month by using two parameters- the year and the month: private _getDaysOfMonth(year: number, month: number): Array<Date& ...

A guide on implementing directives in Angular 2

I am trying to load my navbar.html in my app.component.html by using directives and following the method below: Here is my navbar html: <p>Hi, I am a pen</p> This is my navbar.ts: import {Component, Directive, OnInit} from '@angular/c ...

The fixed header option is not available for the CdkVirtualScrollViewport

Looking for a solution in my Angular application where I need to keep the table header at a fixed position while displaying the scrollbar only on the body part. Currently, I am utilizing the CdkVirtualScrollViewport library in Angular to render the table c ...

In my coding project using Angular and Typescript, I am currently faced with the task of searching for a particular value within

I am facing an issue where I need to locate a value within an array of arrays, but the .find method is returning undefined. import { Component, OnInit } from '@angular/core'; import * as XLSX from 'xlsx'; import { ExcelSheetsService } f ...

Remove a record from Angular 2 Firebase collection

I've been searching extensively for a solution to this problem. Despite following the documentation on AngularFire 2 and Angular 2, I am unable to find a working answer. My goal is simply to delete a specific entry in my Firebase database using its un ...