Toggle the visibility of a text box based on a selected option from a dropdown menu within a dynamic form using Angular

In the form I designed, users have the ability to add one or more divs of Address when they click on the add button.

If a user selects options=5 from the dropdown menu, I want to dynamically show and hide a textbox within that specific Address Div.

Component Code

        get contactFormGroup() {
            return this.form.get('Array') as FormArray;
          }

          ngOnInit() {
            this.form= this.fb.group({
              Array: this.fb.array([])
            });
          }

          createContact(): FormGroup {
            return this.fb.group({
              ABC: [null, Validators.compose([Validators.required])],
              Test: [null, Validators.compose([Validators.required])]
            });
          }

          addContact() {
            this.Group.push(this.createContact());
          }

          showValue(event) {
            const selectedValue = event;
            if (selectedValue === '5') {
                this.showValuetxtbox = true;
            } else {
                this.showValuetxtbox = false;
            }
          }

Answer №1

When iterating through to insert the divs, consider utilizing a template reference variable for the drop down. For example, use #select and then reference it in the *ngIf:

<form [formGroup]="addExpressionform">
    <div formArrayName="expressionArray">
        <div *ngFor="let item of contactFormGroup.controls; let i = index;" [formGroupName]="i">

            <carbon-dropdown #select
                (optionSelected)="showValue($event)"
                [formControlName]="'UOM'"
                [options]="listOptions" [formGroup]="item"
                name="UOM" 
            >
            </carbon-dropdown>

            <carbon-text-input *ngIf="select.value == 5" 
                [formControlName]="'Value'"
                [formGroup]="item"
                name="Value"
            >
            </carbon-text-input>

            <carbon-button type="primary" (click)="submit()" id="save-parameter">Save</carbon-button>

        </div>                  
    </div>
</form>

Check out this simplified StackBlitz demo.

Answer №2

Check out this Angular demo, it's mentioned in the official Angular documentation and can be used as a template for your project.

To organize different types of questions, create separate classes for each one. Then, utilize ngSwitch to dynamically generate corresponding HTML based on the data.

Base question class:

export class QuestionBase<T> {
  controlType: string;
  value: T;
  key: string;
  label: string;
  // other properties

  constructor(options) {
    // constructor logic
  }
}

A specialized class that extends the base class:

import { QuestionBase } from './question-base';

export class SpecialQuestion extends QuestionBase<string> {
  controlType = 'specialQuestion';
  type: string;

  // special Question
  specialValue: string;


  constructor(options) {
    super(options);
    this.type = options['type'] || '';
  }
}

Next, implement a question component:

<div [formGroup]="form">
  <label>{{question.label}}</label>        
  <div [ngSwitch]="question.controlType">
    // add controls here    
    <input *ngSwitchCase="'textbox'" >        
    <select *ngSwitchCase="'specialQuestion'"></select>
  </div>          
</div>

Finally, integrate this into a container component where you iterate through all the questions in the array.

This approach ensures that your code remains flexible and scalable when making changes or additions to form functionality in the future. It eliminates the need for messy solutions to address unique requirements like extra input fields.

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

Assign an attendee the role of organizer in the Google Calendar API

I am currently utilizing the googleapis npm package to facilitate calendar event creation. Below is my request payload for calendar.events.insert in order to generate an event: { "summary":"Biology class", "location":"Google Meet: Please follow the go ...

Ensuring the validity of an HTML form by including onClick functionalities for additional form elements

I am working on a form that I put together using various pieces of code that I found online. My knowledge of HTML and JavaScript is very basic. The form includes a button that, when clicked, will add another set of the same form fields. Initially, I added ...

How come ng-class doesn't apply to a specific class name?

I recently wrote the following code: <style> .dotted { border:dotted; } </style> .... <p ng-style="mystyle" ng-class="dotted">{{ answer }}</p> My intention was to have the paragraph element enclosed within a ...

Ways to periodically create random values and transmit them using MQTT protocol

I need help generating and publishing unique random values to the MQTT protocol every second. Currently, my code keeps sending the same value repeatedly instead of a different one each time. How can I fix this? var mqtt = require('mqtt') var Bro ...

Hiding the original shape with ClipPath in d3 ReactJS

Currently diving into the world of D3 and ReactJS, I attempted to clip a circle with a straight line, but struggled to grasp how it functions. Below is the HTML code snippet used to draw an image: <div> <svg xmlns="http://www.w3.org/2000/svg" ...

Tips for syncing the state data stored in local storage across all tabs with Ngxs state management

After converting the state data to base64 format using the Ngxs state management library, I am saving it. While I can retrieve all data across different tabs, any changes made in one tab do not automatically sync with other tabs. A tab refresh is required ...

Array Scope Lost During Click Event Loop

This Question May Have Been Asked Before: A Practical Example of Javascript Closure inside Loops I am faced with an issue involving an array of 4 objects, each containing a .t property which is a jQuery element. My goal is to assign an event to each t ...

What is the process for implementing the "ngOnActive" life cycle hook in Angular?

Is there a way to implement a life cycle hook that will be triggered whenever my component is active on the main page, specifically on the login page? When my component is on the main page and active, I need to check if there is a login token from a previ ...

What are some techniques for animating SVG images?

Looking to bring some life to an SVG using the jQuery "animate" function. The plan is to incorporate rotation or scaling effects. My initial attempt with this simple code hasn't yielded the desired results: $("#svg").animate({ transform: "sc ...

Tips for differentiating function that accepts various types of arrays with generics

I have come across a typings declaration that caught my attention: public static Loop<Type>(arr:Type[], callback:(obj:Type) => void):void; This declaration represents the structure of a function written in native JavaScript. It essentially itera ...

Problems arising from positioning elements with CSS and organizing list items

I've been working on creating a navigation sidebar using Angular and Bootstrap, but I'm having trouble getting my navigation items to display correctly. APP Component HTML <div class="container-fluid"> <div class="row" id="header"&g ...

Utilizing ngClass and Bootstrap 4 for dynamic styling, fetching class values from Firebase through AngularFire2

Need assistance with retrieving values from Firebase and dynamically sending them to ngClass. Here is my current implementation without Firebase (local only), which is functioning correctly: header.component.html <h3>Header Background:</h3> & ...

When clicking on the side-bar, it does not respond as expected

My website has a menu layout that features a logo on the left and an icon for the menu on the right side. When the icon is clicked, the menu slides in from the right side of the window, and when clicked again, it slides out. However, I am facing two issues ...

Executing a command efficiently in Javascript with the get method

The command that needs to be sent to the embedded device is in the form of a GET method. However, the value continuouspantiltmove: String(pt) is not being properly transmitted to the CGI script through Google Chrome, causing it to fail. Since I do not hav ...

Firefox and Internet Explorer do not support the functionality of HTML5 <audio> tags

My radio stream player code works perfectly on Chrome and iOS Safari, but I'm facing compatibility issues with Firefox and Internet Explorer 11. Here's a snippet from my index.php file: <script type="text/javascript" src="http://code.jquery. ...

Refresh your HTML by reloading the JavaScript source

In my Ubuntu setup, I've been using chart.js to generate a graph displaying the values from a pressure sensor on an HTML document. Most of the project is complete, but I've encountered a challenge for which I haven't found a satisfactory sol ...

Gather and consolidate all files into a single file using Node.js / JavaScript

I currently have 3 JSON files located in my project/Folder file1.json { "id":"01", "name":"abc", "subject":[ "subject1":"Maths", "subject2":"Science" ...

The error message in the lang.js file on line 21 says: "There is a Syntax

https://i.sstatic.net/mLrvW.png Here's my package.json file: "ng2-file-upload": "1.0.3", "ng2-translate": "2.5.0", "angular2-cookie": "1.2.3", "angular2-google-maps": "0.15.0", "key-codes": "0.0.1", "rxjs": "5.0.0-beta.12" "@angular/common": "2.0.0" ...

What is the best way to access the highest level form control within a validator function of a nested form group?

Is there a way to access the complete form within a validator function? I attempted using control.parent.parent, but it resulted in an error. private unitNumberValidator(hasMdu){ return (control: AbstractControl)=>{ let returnVal = null; //I need ...

What is the best way to include rxjs in an npm library - as a dependency, peer dependency, or both?

After researching numerous posts and articles on dependencies versus peerDependencies, I am still not entirely certain what to do in my particular situation.... I have a library (which is published to a private npm repository) that utilizes rxjs; for exam ...