Angular reactive forms are experiencing a setback where the value of '[value]' is not being properly set for controls

My scenario is as follows:

<input #physicalAddress1 type="text" formControlName="PhysicalAddressLine1" />

<tfg-toggle #physicalAsPostal 
            formControlName="PhysicalAsPostal" 
            [onText]="'Yes'" 
            [offText]="'No'"></tfg-toggle>

<input type="text" 
       formControlName="PostalAddressLine1" 
       [value]="physicalAsPostal.value === true ? physicalAddress1.value : ''" />

From the above code, a template reference variable is assigned to 'PhysicalAddressLine1', and if 'PhysicalAsPostal' is selected (true), the value from 'PhysicalAddressLine1' should be copied into 'PostalAddressLine1' [value].

While this behavior works on the UI, the submitted form shows an empty value for 'PostalAddressLine1'.

This is how I retrieve values from the submitted form:

let provider: Provider = Object.assign({}, this.providerFormGroup.value);
console.log(provider.PostalAddressLine1); // Empty string: ""

I am unsure why this is happening. What can I do differently?

Answer №1

Monsterthie, it is not possible to use formControlName and [value] simultaneously. To make the necessary changes, you must directly access PhysicalAddressLine1.controls.PostalAddressLine1.value. You can implement this change in the .ts file after creating the form. For example: (*) Implement a component that utilizes OnInit and OnDestroy

alive=true; //<--declare a variable
ngOnInit(){
  this.form=this.fb.group(...)
  this.form.controls.PhysicalAddressLine1.valueChanges
     .pipe(takeWhile(()=>this.alive))
     .subscribe(res=>{
       this.form.controls.PostalAddressLine1.setValue(res?res:'')
     })
}
ngOnDestroy()
{
   this.alive=false;
}

NOTE: I have included a standard structure for unsubscribing when the component is destroyed

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

Tutorial on declaring and initializing a variable within an HTML template in Angular

I have come across this question on Stackoverflow before, but the solutions provided did not work for me. I am attempting to iterate through a list of categories and items. I only want to display each category once, so I need to check if the current categ ...

What causes the cursor in an editable div to automatically move to the front of the div?

<div className="min-w-[600px] min-h-[36.8px]" > <div id={`editableDiv-${Object.keys(item)}-${index}`} className="p-3" contentEditable suppressContentEditableWarning onInput={(e) => onChange(e)} > ...

Issue with Ant Design form validation

After reading through the documentation, I attempted to implement the code provided: Here is a basic example: import { Button, Form, Input } from "antd"; export default function App() { const [form] = Form.useForm(); return ( <Form f ...

Issue encountered with ngFor: 'Identifier not defined __type does not have any such member'

Recently, I successfully implemented a sub-component that allows users to dynamically add and remove a set of controls to and from a collection. The inspiration for this solution came from reading through this particular thread on Stack Overflow. While ev ...

What is the best way to make two buttons align next to each other in a stylish and elegant manner

Currently, I am diving into the world of glamorous, a React component styling module. My challenge lies in styling two buttons: Add and Clear. The goal is to have these buttons on the same row with the Clear button positioned on the left and the Add button ...

Storing the data object in an array using Angular and Mongoose in Node.js

I've encountered an issue with my Angular form connected to Node JS and MongoDB. While some data from the form gets saved in mongoDB, there are certain fields like measurementUsed and testTolerance that do not get saved properly. This is how my model ...

Encountering an error when setting up a React-TypeScript ContextAPI

I am currently attempting to understand and replicate the functionality of a specific package found at: https://github.com/AlexSegen/react-shopping-cart Working within a React-Typescript project, I have encountered challenges when creating the ProductCont ...

Angular doesn't support this particular type as an injection token

I'm attempting to create a constructor with a type of string, but I keep encountering the following error: This particular type is not supported as an injection token @Injectable({providedIn: 'root'}) export class DataService { const ...

Tips for dynamically updating the Header name based on backend data

I am currently utilizing ag-grid within my Angular application. Within the columnDefs array, I have defined headers for my grid. One of the headers is for a column labeled Amount. My goal is to make this header dynamic, so that if the currency value coming ...

Encountering unexpected errors with Typescript while trying to implement a simple @click event in Nuxt 3 projects

Encountering an error when utilizing @click in Nuxt3 with Typescript Issue: Type '($event: any) => void' is not compatible with type 'MouseEvent'.ts(2322) __VLS_types.ts(107, 56): The expected type is specified in the property ' ...

`What is the best way to transfer an observable to a child component?`

I am facing an issue with passing an Observable down to a child component. I have tried various solutions but none seem to work. parent.component.ts: export class ParentComponent { items$ = of([{name: "Item 1"}, {name: "Item 2"}]); } ...

Cyrillic characters cannot be shown on vertices within Reagraph

I am currently developing a React application that involves displaying data on a graph. However, I have encountered an issue where Russian characters are not being displayed correctly on the nodes. I attempted to solve this by linking fonts using labelFont ...

Issue with Angular ngFor not updating radio button value when ngModel is set

Hello, I am fairly new to working with Angular and could really use some assistance with a problem I've run into. Essentially, I am receiving an array of objects from an API like this: [{name: "abc", score: 2},{name: ""def, score: ...

Can Next.js accommodate server-side redirection with internationalization?

I'm working on a small Next.js app that has pages accessible only to logged in users. To manage the authenticated routes, I created an HOC (withAuth) that handles redirection on the server side to prevent page flashing on the client side. Everything i ...

A guide to using Angular to emphasize text based on specific conditions met

Currently, I am developing a testing application that requires users to choose radio type values for each question. The goal is to compare the selected answers with the correct answers stored in a JSON file. To achieve this, I have implemented an if-else ...

Node modules are incapable of being installed within node packages

Whenever I use the ng serve command in my terminal, an error pops up: 10% building 3/3 modules 0 activei 「wds」: Project is running at http://localhost:4200/webpack-dev-server/ i 「wds」: webpack output is served from / i 「wds」: 404s will fall ...

Utilize a custom Angular2 validator to gain entry to a specific service

For accessing my custom http service from within a static method, consider the following example: import {Control} from 'angular2/common'; import {HttpService} from './http.service'; class UsernameValidator { static usernameExist( ...

An error has occurred in Angular2 and Ionic 2, where there is a TypeError preventing the reading of the property 'addEventListener' in the InAppBrowser

When attempting to open a remote address in my app using the Cordova plugin InAppBrowser, I encountered an issue with the following code: import { Injectable } from "@angular/core"; import { HttpQueryService } from "./httpqueryservice"; import { ToastCo ...

Using Typescript: invoking static functions within a constructor

This is an illustration of my class containing the relevant methods. class Example { constructor(info) { // calling validateInfo(info) } static validateInfo(info):void { // validation of info } I aim to invoke validateInfo ...

Update 2020: The data pathway ".builders['app-shell']" must include the mandatory property 'class'

Having exhausted all options in various forums, including StackOverflow, without success. Tried and failed: npm uninstall @angular-devkit/build-angular npm cache clean -f npm install @angular-devkit/build-angular Deleted the node_modules folder and ...