Angular Reactive Forms may not properly update other inputs when binding a control to multiple inputs

While working with reactive forms, I encountered an issue where accessing the same control in multiple inputs seemed to result in one-way data binding (input-to-model). If I make edits in one input, it updates the model correctly but does not refresh the other input as expected.

<input type="text" formControlName="test" id="in1">
<input type="text" formControlName="test" id="in2">

To address this, I found a workaround by adding the following line to both inputs:

(change)="form.controls.test.setValue(form.controls.test.value)

However, I believe this solution is not ideal. Am I missing something here? What is the proper way to achieve the desired outcome?

https://plnkr.co/edit/yALzCIHgOA463OvGi5rP

Answer №1

It may not be clear why you would require two fields with the same formControlName, but one possible solution is to create a custom angular element.

@Component({
  selector: 'custom-element',
  templateUrl: `
    <input type="text" [(ngModel)]="value">
    <input type="text" [(ngModel)]="value">
  `,
  styleUrls: ['./custom-element.component.css']
})
export class CustomElementComponent implements ControlValueAccessor

@Input() value: any 

writeValue(value: any) {
  // Include some conditional statements
  this.value = value;
}

registerOnChange(fn: Function) {
  // Add your implementation here
}
registerOnTouched(fn: Function) {
  // Add your implementation here
}

In the parent component template, include:

<custom-element formControlName="fieldname"></custom-element>

For additional insights and in-depth explanations, refer to

Answer №2

To implement two-way binding, you can utilize ngModel:

<div>
    <form [formGroup]="form">
        <h2>Test = {{form?.controls.test.value}}</h2>
        1. <input type="text" formControlName="test" [(ngModel)]="test"> 
    2. <input type="text" formControlName="test" [(ngModel)]="test"> 
    3.
        <button type="button" (click)="form.controls.test.setValue('manual')">change with setValue</button>
    </form>
</div>

Essentially, the two-way binding syntax simplifies a combination of property and event bindings.

For instance:

<app-sizer [(size)]="fontSizePx"></app-sizer> 

Can be written as:

<app-sizer [size]="fontSizePx" (sizeChange)="fontSizePx=$event"></app-sizer>

VIEW CODE EXAMPLE

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

Passing Props from _app.js to Page in ReactJS and NextJS

I recently made the switch from ReactJS to NextJS and am encountering some difficulties in passing props from _app.js to a page. My issue lies in trying to invoke a function in _app.js from another page. In ReactJS, this process was simple as you could cr ...

Determining the optimal number of rows and columns based on an integer value

Here's a brain teaser for you: /** * Let's figure out the optimal number of rows and columns for your garden to be as square as possible, based on the number of seeds you have. * * @param {number} seedCount - The total number of seeds in you ...

Sliding horizontally with a responsive touch

I am looking to implement a horizontal responsive page navigation, similar to the illustration shown below: This is my current progress: DEMO $(document).ready(function () { var slideNum = $('.page').length, wrapperWidth = 100 * s ...

Tips for Passing the correct ID to the modal component in reactJs

Looking for some assistance. The issue I'm encountering is that the modal isn't displaying the correct ID of the data I wish to delete Here is my DataTable.jsx code: import React, { useState, useEffect } from "react"; import axios from ...

What is the best way to transmit error messages from the server to the client?

I am currently working on my express server and I have a query regarding how to efficiently communicate error messages to the client side. My goal is to display the error message both on the client console as well as on the server console, but I am uncerta ...

Footer button overrides list components due to improper implementation of vertical ion-scroll

Having some trouble setting up ion-scroll on a specific screen in my mobile application built with Ionic. On the Book page of my app, I'm encountering two main issues: https://i.stack.imgur.com/MnheG.png 1) The placement of the Confirm button doesn& ...

A type error was thrown: $.ajax function does not exist within another function

I encountered a persistent ajax error on the website. Error : Uncaught TypeError: $.ajax is not a function at Hei Here is my code for reference: Can anyone pinpoint where I may be going wrong? The suggested solutions from other sources have not resol ...

Display of Navigation Bar in Angular is Not Proper

Currently diving into the world of Angular, I've encountered an issue with a material menu that isn't displaying correctly. The expected outcome based on my code should resemble this image: https://i.stack.imgur.com/z70Aq.png This snippet showc ...

Obtain Relative URL with the help of Selenium using the PhantomJS driver

Utilizing Selenium along with the Phantom JS driver, I am attempting to load an HTML page and extract all of the HREF links from it. The issue arises when PhantomJS provides absolute URLs after resolving them entirely. My specific requirement is to extrac ...

Identify the primary application using a hybrid application

I am currently working on a project to create a desktop application using angular2 and Electron that can run seamlessly across different platforms. One of my main challenges is being able to identify the foreground process running on the computer, regardle ...

Accept only requests from my Chrome extension

I have successfully set up a NodeJS server with Express on DigitalOcean. My Chrome extension is able to make GET calls to the server without any issues. However, I am looking to enhance the security of the middleware below: // Add headers app.use(function ...

NEXT JS - Application renders twice due to rewrites in place

I'm currently working on a NEXT JS project and facing the issue of the app rendering twice! Challenge After implementing rewrites in next.config.js, the app is being rendered twice. Removing the rewrites solves the issue and only renders once. next ...

The JQuery error encountered was due to a missing colon after the property ID

I'm currently working on some jQuery code that is supposed to hide one paragraph and show another when a specific action is triggered. I have created a class called "showp" which displays the targeted paragraph while ensuring that other paragraphs are ...

Is there a way to leverage the extensive Bootstrap 5 color palette within an Angular application?

Currently working on a project in Angular 12 with Bootstrap 5 and SCSS, I'm facing a challenge in utilizing the new extended Bootstrap 5 color palette such as indigo-300 or pink-200. I'm not sure if I need to import them in a certain way or how t ...

Angular2 displays an error stating that the function start.endsWith is not recognized as a valid function

After switching my base URL from / to window.document.location, I encountered the following error message: TypeError: start.endsWith is not a function Has anyone else experienced this issue with [email protected]? ...

The argument represented by 'T' does not align with the parameter represented by 'number' and therefore cannot be assigned

I am confused as to why, in my situation, <T> is considered a number but cannot be assigned to a parameter of type number. Changing the type of n to either number or any resolves the issue. Error: https://i.sstatic.net/h1GE9.png Code: const dropF ...

"Encountering an Error with Route.get() when attempting to utilize an imported

I have a function that I exported in index.js and I want to use it in test.js. However, when I try to run node test, I encounter the following error message: Error: Route.get() requires a callback function but got a [object Undefined] What am I doing wro ...

Looking to display a div with both a plus and minus icon? Having trouble getting a div to show with left margin? Need assistance hiding or showing div text

Can someone please review this source code? Here is the demo link: http://jsfiddle.net/bala2024/nvR2S/40/ $('.expand').click(function(){ $(this).stop().animate({ width:'73%', height:'130px' }); $( ...

Troubleshooting NativeScript 5: Uncovering the iOS Memory Woes of Crashes and Le

Check out this link for more information: https://github.com/NativeScript/NativeScript/issues/6607 Software Stack: NativeScript 5 Angular 7 Demo repository: https://github.com/reposooo/ns-out-of-memory This issue is based on a similar problem i ...

In Ionic 4, a special character is showing up before the form tag

I'm facing a bizarre issue with my Ionic 4 app... a strange character is appearing before the form https://i.sstatic.net/Y7Txh.png I tried using Google DevTools, but I couldn't identify how this extra character is being injected before the form ...