What is the process for assigning a value to a property?

I am currently developing an Angular application that utilizes reactive forms. I need to retrieve the values of dynamically created fields within a form group. Here is the code I have implemented:


        this.formSaisieSecondary = this.fb.group({
            options: this.fb.array([])
        });

        newOption(): FormGroup {  
            return this.fb.group({  
                date: ['', Validators.required],
                cargoA: ['', Validators.required],
                cargoB: ['', Validators.required],
                cargoC: ['', Validators.required],
                cargoD: ['', Validators.required],
                cargoE: ['', Validators.required],
                unite: [this.unite, Validators.required],
                siloA: ['silo1', Validators.required],
                siloB: ['silo2', Validators.required],
                siloC: ['silo3', Validators.required],
                siloD: ['silo4', Validators.required],
                siloE: ['silo5', Validators.required],
                comment: [''] 
            })  
        }

        options(): FormArray {  
            return this.formSaisie.get("options") as FormArray;
        }

        AddOption() { 
            this.options().push(this.newOption()); 
        }
    

Here is the corresponding HTML code:


        <form [formGroup]="formSaisie">
            <div formArrayName="options">
                <div class="row mb-5" style="height: 23px;" *ngFor="let option of options().controls; let i = index" [formGroupName]="i">
                    <div class="col-md-1">
                        <input formControlName="date" type="text" formControlName="date" hidden [(ngModel)]="listDate[i]">
                        <p>{{listDate[i]}}</p>
                    </div>
                    <div class="col-md-2">
                        <mat-form-field class="inputGridItem" appearance="fill">
                            <mat-label>Cargaison</mat-label>
                            <mat-select formControlName="cargoA" required>
                                <mat-option *ngFor="let cargo of dataEx" [value]="cargo.cargoId">
                                    {{cargo.vessel + " " + cargo.externalId}}
                                </mat-option>
                            </mat-select>
                        </mat-form-field>
                    </div>
                    .............
    

The code was inspired by a similar approach found here.

My question pertains to how I can both retrieve and set values for the form fields. For example, to retrieve a value, I can do the following:


        let value = this.formSaisie.value.options[0];
        value.cargoA;
    

However, I am unsure of how to set a value for a field.

Answer №1

this.options().at(0).get('cargoA').setValue(newValue)

This line of code assigns a new value to the cargoA property of the group located at index 0 within the form array.

It is worth noting that it is highly advised not to mix ngModel and reactive forms within the same form, as they may conflict with each other and lead to unpredictable behavior.

Answer №2

If you want to set a value, you can achieve it by using the following code snippet:

this.formSaisie.get('cargoA').setValue(newValue)

update: To set the value in nested form controls, you can do it like this:

this.formSaisie.get('options').get('cargoA').setValue(newValue)
- give it a try and see if it works

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

Discover the security vulnerabilities in Node.js when using VS Code with FREECODECAMP's React app

As a beginner in using VS code, I attempted to work on a project for FREECODECAMP. This project involved creating a random quote machine, marking my first time coding a react project. While following a YouTube tutorial and making progress towards functiona ...

The issue at hand is the lack of execution for the Mocha Chai `.end()`

I have encountered an issue while trying to write a Mocha chai test for a Nodejs API that was previously tested using Supertest. Strangely, the test always passes even when I intentionally specify wrong expected parameters. Below is the code snippet of th ...

What is the best way to apply changes to every class in JavaScript?

Check out this HTML and CSS code sample! body{ font-family: Verdana, Geneva, sans-serif; } .box{ width: 140px; height: 140px; background-color: red; display: none; position:relative; margin-left: auto; margin-right: auto; } .bold{ font ...

How to retrieve the HTTPClient value in Angular?

APIservice.ts public fetchData(owner: any) { return this.http.get(`${this.url}/${owner}`, this.httpOptions).pipe( catchError(e => { throw new Error(e); }) ); } public fetchDataById(id: number, byId:string, owner: any) { ...

(Typescript) The 'window' property is not present in the 'Global' type

Currently, I am utilizing Mocha/Chai for unit testing and have decided to mock the window object like so: global.window = { innerHeight: 1000, innerWidth: 1000 }; As expected, TSLint is raising an issue stating: Property 'window' does not ex ...

What is the method to modify the background color of el-pagination?

I am using el-pagination on a dark page and I want to make its background color transparent. When I do not use the 'background' prop, the background color of el-pagination is white. Here is how it looks: (sorry I can't add an image) htt ...

Utilizing Angular2 (Frontend) and Spring Boot (Backend) for Excel file uploading

As someone who is new to Angular 2, I am currently attempting to upload an Excel file from the Angular 2 frontend. My goal is to upload the Excel file from the Angular 2 frontend, send it to the Spring Boot backend for necessary modifications, and th ...

Interactive Sidebar Navigation Content

On my website, I have a navigation sidebar that contains links to all of the main site pages. Each page has the same links, except the link to the current page is not included, making it easy to visually identify which page you are on. Currently, I manuall ...

On what occasion is a DOM element considered "prepared"?

Here's a question that might make you think twice: $(document).ready(function() { }); Sometimes, the simplest questions lead to interesting discussions. Imagine having a list of elements like this: <body> <p>Paragraph</p> < ...

Exploring the dissimilarity among npm run dev and the parcel index.html

I have been using parcel index.html to set up a local development server, bundling, and hot module replacement. However, I recently learned that npm run dev can do something similar. This has left me wondering: What are the distinctions between the two me ...

Incorporate pictures from the popup onto the main page

I have developed a basic PHP image editor script where users can select images from galleries and merge them together. However, I am facing an issue: The galleries open in a popup while the editor area is on the parent page. I am looking for a JavaScript ...

Choose a HTML element <a> containing a hyperlink reference and a nested child element <li>

Does anyone know of a way in javascript/css to select the (n) <li> in my code, while also specifying that the <li> must have a parent with the current <a> tag containing a specific href link? <a href="www.link.com">CATEGORY NAME& ...

Tips on how to showcase it to cover a wide area

I'm having trouble figuring out how to display the output in a span element. Every time I try, I just get a blank result, and when I alert the txtNumber variable, I see "object html span element" in the alert message. <span id="displayQty"> num ...

Collection of clickable images that lead to creatively designed individual pages

Being relatively new to JavaScript and jQuery, my knowledge is solid when it comes to HTML & CSS. Currently, I have a page with 20 minimized pictures (with plans to increase to 500+ images) that open into a new page when clicked. Although I have no issues ...

What is the best way to connect multiple web pages together?

Hello everyone, I could really use some assistance with a problem I'm facing. As a newcomer to web development, I have a question about navigation bars. I've successfully created a basic webpage with a navigation bar, but now I'm unsure how ...

Storing images in Azure Blob Storage

I am currently using Angular 2 on the frontend and Node.js for the backend. I am facing an issue while attempting to upload a file to Azure storage blob container. Whenever I try to send the image to the API, an error occurs. Any assistance in this matter ...

Incorporating external Angular 4 components within my custom components

For my project, I am attempting to incorporate jqWidgets Angular components: import { Component, ViewChild } from '@angular/core'; import 'jqwidgets-framework'; import { jqxTreeComponent } from "jqwidgets-framework/jqwidgets-ts/angula ...

Failure to send Websocket connection

Currently working on PHP, here's a snippet: $room_array = array(); $room_array[0] = 'room-list'; $room_array['info'] = array('room_name' => $room['room_name'], 'owner' => $username['usernam ...

Transform a nested JSON Object into a customized array structure

My task involves converting a nested JSON object into a specific format, as demonstrated below: let jsonObj ={"data": { "cardShop": { "cardData": { "cardTitle": "The Platinum Card<sup> ...

Using PHP and MySQL to handle data submission through the POST method

When I send data to post[submit] and post[request], it's coming from two separate buttons. Even though I successfully submitted user_id to post[submit], I'm encountering difficulty in echoing the user_id in the request portion (post[request]). ...