Disabling FormArray on-the-fly in Angular

I have a scenario where I need to disable multiple checkboxes in a FormArray when the page loads. Despite my attempts to implement this, it hasn't been successful so far. Can someone provide guidance on how to achieve this?

.ts file

public myForm: FormGroup = new FormGroup({
    name: new FormControl('', Validators.required),
    specialized: new FormArray([]),
  });

ngOnInit(): void {
      this.companyForm.controls['specialized'].disable();
}

  get myFormArray() {
    return this.myForm.controls.specialized as FormArray;
  }

  private addCheckboxesToForm() {
    this.specilizedArea.forEach(() => this.myFormArray.push(new FormControl(false)));
  }

.html file

<form [formGroup]="myForm">
    <div class="form-check col-md-6"
                                *ngFor="let order of myFormArray.controls; let i = index">
    
                                <label formArrayName="specialized">
                                    <input type="checkbox" [formControlName]="i">
                                    {{specilizedArea[i]?.description}}
                                </label>
    
                            </div>
     <button (click)="saveCompany()"> ADD</button>
    </form>

Answer №1

When initializing the component in Angular, make sure to include a call to the method addCheckboxesToForm. Within this method, create FormControls with the property disabled: true, as shown below:

private addCheckboxesToForm() {
    this.specilizedArea.forEach(() => this.myFormArray.push(new FormControl({value: false, disabled: true})));
  }

I have provided an example using your code on StackBlitz: https://stackblitz.com/edit/angular-ivy-bmnfcd?file=src/app/app.component.ts

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

Encountering errors with React Bootstrap during the build process

Currently, I am working on a Nextjs project integrating React bootstrap. Everything was functioning smoothly until today when all of the React bootstrap components started throwing the same error, leading to build failures. The 'Dropdown.Item' co ...

When using TypeScript, how can I effectively utilize the Component property obtained from connect()?

Software Development Environment TypeScript 2.8 React 16 Redux Foo.tsx interface IFooProps{ userId:number } class Foo extends Component<IFooProps>{ render(){ return <p>foo...</p> } } const mapStateToProps = (state: I ...

Guide on accessing intellisense for mapGetters, mapActions in Vuex using TypeScript without the need for class-style or decorators syntax

I have been using Vue.js and Vuex for a while now, but always with JavaScript. Recently, I decided to try using Vue with TypeScript, specifically with nuxt.js, but without utilizing decorators or style-class-components. I want to stick to the normal Vue s ...

How to display the Y axis value on the category axis in a solid gauge using amcharts

My Code : <div id="chartdiv"></div> Styling : #chartdiv { width: 100%; height: 200px; } Script: am4core.useTheme(am4themes_animated); var chart = am4core.create("chartdiv", am4charts.RadarChart); chart.data = [{ ...

Is there a way to activate custom and default validators for validation on an ng2 template form?

Within my ng2 form, I am utilizing a control that looks like this: <input class="form-field" type="text" id="fieldName" name="fieldName" #fieldName="ngModel" (ngModelChange)="onFieldNameChange($event)" [(ngModel)]="model.f ...

Leveraging AWS SSM in a serverless.ts file with AWS Lambda: A guide to implementation

Having trouble utilizing SSM in the serverless.ts file and encountering issues. const serverlessConfiguration: AWS = { service: "data-lineage", frameworkVersion: "2", custom: { webpack: { webpackConfig: "./webpack ...

issue with uploading files in angular 7

Currently, I am facing an issue with Angular 7 where the input type "file" is not working as expected. However, in Angular 6, everything works fine. When submitting the input file type data in Angular 6, I receive a field list like this: https://i.sstat ...

Exploring the method to retrieve data on the server side through Express when it is shared by the client within a put request

Here is the angular http put request I am working with: sendPutRequest(data) : Observable<any>{ return this.http.put("http://localhost:5050", data).pipe(map(this.handleData)); } After making this call, the server side method being invoked is ...

Is there a way to attach numerical values to CSS in order to generate a timeline effect?

My goal is to arrange div elements on a timeline based on an array of floats ranging from 0 to 1. The idea is to have the elements positioned along the timeline according to these float values, with 0 representing the beginning and 1 indicating the end. ...

Adding a total property at the row level in JavaScript

Here is a JavaScript array that I need help with: [{ Year:2000, Jan:1, Feb: }, {Year:2001, Jan:-1, Feb:0.34 }] I want to calculate the total of Jan and Feb for each entry in the existing array and add it as a new property. For example: [{ Year:2000, Ja ...

What is preventing me from connecting to dockerized npm from my host machine?

Issue - A server running inside a docker container is not responding when accessed from outside the container on an OSX host. web: image: my_web build: context: ./ dockerfile: web.docker container_name: my_web networks: ...

What is the process of assigning a value type to a generic key type of an object in typescript?

I am currently working on developing a function that can merge and sort pre-sorted arrays into one single sorted array. This function takes an array of arrays containing objects, along with a specified key for comparison purposes. It is important to ensure ...

What could be causing the Properties Array to come back as undefined?

When attempting to add an item to an array stored in the properties, I am encountering an error: "Cannot read properties of undefined (reading 'value')." Within the props, the following interfaces are defined: ILinkItemProps.ts export interface ...

When I try to use http-server with the port 8080, my Angular application is not being served. However, when

Upon opening my localhost, this is the view I encounter My goal is to create a Progressive Web App (PWA) using Angular. I meticulously followed the guidelines outlined on the angular.io site, yet it does not display the standard "Welcome to your app" page ...

Is React Spring failing to trigger animations properly on iOS devices?

I have a code that functions perfectly on my desktop and across all browsers. Each button is designed to trigger a 4-second animation upon load or hover, initiating the playback of various videos. However, there's an issue with iOS where the video or ...

Should data objects be loaded from backend API all at once or individually for each object?

Imagine having a form used to modify customer information. This form includes various input fields as well as multiple dropdown lists for fields such as country, category, and status. Each dropdown list requires data from the backend in order to populate i ...

The "initialized" event in angular2-tree-component fires prior to the data being loaded

Utilizing the angular2-tree-component, my goal is to display an already expanded tree. According to Angular docs, the initialized event should be used for expanding the tree after the data has been received: This event triggers after the tree model has ...

Is it possible to utilize a function within an Angular [routerLink] to define the query parameter?

When receiving a response from the API without an ID, it presents data fields like url, name, gender, culture, etc. However, I need to create a route to access specific character information using /characters/:id. Since there is no direct ID provided in th ...

Sort the elements within the *ngFor loop according to the category upon clicking the button in Angular

Currently, I have a collection of items that I am iterating through using *ngFor. Above this list, there are category buttons available as shown in the HTML snippet below. My goal is to enable filtering of the list based on the category of the button click ...

Using the appropriate asynchronous action in Redux with the Redux-Thunk middleware

While learning middleware redux-thunk, I created a simple React App. However, I am facing a transpilation issue due to an incorrect type of async action fetchPosts in the interface PostListProps. Below is the code snippet of the functional component where ...