"Disabling a FormControl within a FormArray in Angular 4: A Step-by-

I've come up with a code snippet below that I thought would disable the FormControl in a FormArray.

some.component.html

<form [formGroup]="testForm">
    <div *ngFor="let num of countArr">
        <input type="text" formNameArray="arrs">
    </div>
</form>

some.component.ts

countArr = [1, 2, 3, 4, 5];
count = 5;
arrs;
testForm: FormGroup;

this.testForm = this.formBuilder.group(
    arrs: this.formBuilder.array([])
);

this.arrs = this.testForm.get('arrs');

for (let i = 0; i < this.count; i++) {
    this.arrs.insert(i, new FormControl({value: '', disabled: true}));
}

However, after running the loop, I checked the form and noticed that nothing had been disabled. Can you please point out where I might be going wrong? :-)

Your assistance is greatly appreciated!!! :-)

Answer №1

To start, this is the proper structure for your HTML component:

<form [formGroup]="testForm">
    <div formArrayName="arrs">
        <div class="form-group" *ngFor="let arrItem of testForm.get('arrs').controls; let i = index">
            <input type="text" class="form-control" [formControlName]="i">
        </div>
    </div>
</form>

There's no need to loop through a random count variable in your HTML. Instead, iterate over your added controls.

You might be wondering, "Which controls specifically? They haven't been added yet!"

This is where you dynamically add those controls in the ngOnInit method:

ngOnInit() {
    this.testForm = new FormGroup({
      arrs: new FormArray([])
    }
    );

    for (let i = 0; i < this.count; i++) {
      const control = new FormControl(null, Validators.required);
      (<FormArray>this.testForm.get('arrs')).push(control);
    }

    this.disableInputs();
}

Here is the correct syntax for initializing the FormArray, creating an initial control inside the for loop, and adding the new control to your array.

Important: there is a call to the disableInputs() function. This is where you programmatically disable your inputs as well:

  disableInputs() {
    (<FormArray>this.testForm.get('arrs'))
      .controls
      .forEach(control => {
        control.disable();
      })
  }

Here is a functional example: stackblitz

Answer №2

To activate Dynamic Input functionality, follow these steps:

form: FormGroup;
  orders = [
    { id: 100, name: 'order 1' },
    { id: 200, name: 'order 2' },
    { id: 300, name: 'order 3' },
    { id: 400, name: 'order 4' }
  ];

  constructor(private formBuilder: FormBuilder) {
    const controls = this.orders.map(c => new FormControl(''));

    this.form = this.formBuilder.group({
      orders: new FormArray(controls)
    });

    this.form.get('orders').controls
      .forEach(control => {
        control.disable();
      })
  }

Your HTML code should resemble the following structure:

<form [formGroup]="form" >
  <label formArrayName="orders" *ngFor="let order of form.controls.orders.controls; let i = index">
    <input type="text" [formControlName]="i">
    {{orders[i].name}}
  </label>
</form>

Answer №3

Utilize the formArray control within the loop to assign it to each input:

<form [formGroup]="testForm">
    <div formArrayName="arrs">
        <div *ngFor="let num of countArr; let idx = index">
            <input type="text" [formControlName]="idx" [attr.disabled]="true">
        </div>
    </div>
</form>

You may find more information in this article:

https://angular.io/guide/reactive-forms#display-the-formarray

Answer №4

Deactivating the FormControls within a FormArray can be achieved effortlessly using the "reset" method.

this.formGroupHere.get(['formArrayHere']).reset({
        disableFields: {
            formControlHere: true,
            otherFormControl: true
        }
    }
);

Answer №5

To achieve this, you can disable the formControl during initialization or updating by following these steps:

In this scenario, let's assume that testForm represents the formGroupName, arrs is the FormArrayName, and inputValue corresponds to the formControlName

(<FormArray>this.testForm.get('arrs')).push(new FormGroup({
  'inputValue': new FormControl({ value: '', disabled: true }, Validators.required),
}));

Please note that disabling the form input will prevent submission. Alternatively, you can utilize the readonly property as demonstrated below.

<input readonly="readonly" type="text" />

This method allows you to retrieve input values from the form effectively.

Refer to the source for more information on using the "readonly" attribute.

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

Is there a way for me to retrieve the header values of a table when I click on a cell?

I have a project where I am developing an application for booking rooms using Angular 2. One of the requirements is to be able to select a cell in a table and retrieve the values of the vertical and horizontal headers, such as "Room 1" and "9:00". The data ...

The request for XMLHttpRequest has been restricted from accessing ASP.NET CORE 2.2.0 with Angular 8 and signalr1.0.0 due to a failure in the CORS policy (Access-Control-Allow-Origin)

nugetPackage on .net core2.2.0: signalr 1.0.0 + ASP.Core2.2.0 I am utilizing angular to utilize signalr: package.json: "@aspnet/signalr": "1.1.0", my front-end Angular code: import { Component } from '@angular/core'; import * as signalR fro ...

Creating auto serial numbers in the MERN stackWould you like to know how to

I need help coming up with a way to automatically generate serial numbers for my "ticketno" field. Every time a user creates a new application ticket, the ticket number should increment by one. Can someone guide me on how to achieve this? This i ...

Code Not Functioning on Website Despite Working in Console

I've developed a jQuery script that eliminates any delivery methods containing the phrase "Royal Mail" if certain products are present in the user's cart. The script functions flawlessly when executed in Google Chrome Console but fails to work wh ...

Displaying a JQuery loading image on a webpage for a designated amount of time

I am trying to display an image in a div once a price calculation function is called. The image should cover the whole page. Can someone assist me with this? <div class="Progress_Layout" style="display:none"> <div class="Progress_Content"> ...

In a Django template, implement a checkbox feature in the list view to select multiple objects. Retrieve all selected checkbox objects for each pagination and display them in

In my HTML template, I have a list view with checkboxes and pagination. My goal is to retrieve all the checked box objects from each page's pagination and send them to the server (specifically the view part of Django). For example, if I check 4 object ...

Uploading information to a server using Angular.js

I am currently working on developing an application with the following code snippet: function attendeeCtrl($scope, $http) { $scope.submit = function () { console.log($scope.noattendees); $http({ method: 'POST', ...

What is the process for configuring simultaneous services on CircleCI for testing purposes?

My current project involves running tests with Jasmine and WebdriverIO, which I want to automate using CircleCI. As someone new to testing, I'm a bit unsure of the process. Here's what I've gathered so far: To run the tests, I use npm tes ...

Retrieve the element that triggered the event listener within Nuxt

I am currently developing a Nuxt project where I have set up my component using the code below. The select-parent-container has a click event attached to it. Whenever this event is triggered, I need to identify and return the specific parent container that ...

Forward after asynchronous JavaScript and XML (AJAX)

Currently, I am working on an MVC project where I need to achieve the following: The scenario involves sending an ajax request from a JS script and then redirecting to a page along with a model once the request is processed. I attempted to send a form as ...

Error: The function window.intlTelInput is not recognized within the ReactJS framework

I am currently learning ReactJS and encountering an issue when using jQuery with React JS for intlTelInput. I have installed npm jQuery and imported all the necessary code. Additionally, I have included all the required CSS and jQuery links in my index.htm ...

PHP array utilized in a dynamic dropdown menu

I am working on creating a PHP array for a select list that has dynamic options populated using JavaScript. My goal is to collect all the options selected and display them on the next page. I was wondering if there is a better way to achieve this task. C ...

Is the CSS scale activated by mouseover or click?

My CSS code successfully scales images, but the issue is that it affects every image on the page. I am looking for a solution to apply this CSS only when the user hovers over or clicks on an image. The challenge is that images are added by non-technical w ...

JavaScript Popup prompting user on page load with option to redirect to another page upon clicking

Can a JavaScript prompt box be created that redirects to a site when the user selects "yes" or "ok," but does nothing if "no" is selected? Also, can this prompt appear on page load? Thank you! UPDATE: Answer provided below. It turns out it's simpler ...

Rails javascript not triggering even after the page is loaded with `page:load`

My experience with using Stripe in Rails has been smooth, except for some issues with Ajax calls not working properly after page refresh. I suspect this might be related to Turbolinks as the 'ready page:load' event doesn't behave as expected ...

Discover the best way to retrieve attribute values using jQuery

I'm struggling to retrieve the value of the attribute "_last_val" from my input, but I'm having trouble getting it. Here is what I have attempted: demo // Here is the HTML code <form method="post" action="" id="feedback_form"> <inpu ...

Using the Jquery accordion function within google maps is limited to running only one time

After successfully creating a google maps page with markers generated from XML, I encountered an issue. The plan was to display event information in a div when a marker is clicked, along with attaching an accordion to the events data. Although the first cl ...

Issue with printing JavaScript value using Selenium_ASSUME_WE_NOT have any changes in the content

I'm currently running tests with Selenium and Java. I've experienced success in printing the pages' HTML from JavaScript by using an alert: js.executeScript("alert($('html').html());"); However, when trying to use return, nothing ...

Form featuring a mandatory checkbox that must be selected in order to proceed; failure to do so will result in an

So here’s the situation: I have a form with a checkbox for agreeing to the terms of service, and I want to make sure it is checked before proceeding with the donation process. I only have the HTML code and no idea how to implement this functionality. Ide ...

Animating toasts in Bootstrap

Exploring the options available at https://getbootstrap.com/docs/4.3/components/toasts/ To customize your toasts, you can pass options via data attributes or JavaScript. Simply append the option name to data- when using data attributes. If you're lo ...