Angular: When custom form components fail to respond to changes in value, it can feel as if the two-way data binding feature

Currently, I am working on developing my own custom form component that is facing a similar issue to the one discussed in this article

I have forked the code mentioned in the article to demonstrate the issue ... https://stackblitz.com/edit/angular-8afwjx?file=src/app/app.component.html

In the example using ngModel, any change in one element automatically updates another due to two-way data binding.

However, with reactive forms and formControlName bindings, toggling one control does not update the other control as expected.

I am exploring ways to ensure my custom control reacts correctly to value changes. Should I subscribe to it? It seems somewhat challenging.

Answer №1

By using the formControl directive, you have the ability to bind a single form control instance to multiple inputs. To ensure that these controls stay synchronized, you can simply set the value property of the form control.

<form [formGroup]="myForm" (ngSubmit)="submit()">
  <label for="switch-2">Reactive Forms</label>
  <app-switch id="switch-2" [value]="switchControl.value" [formControl]="switchControl"></app-switch>

  <label for="switch-2">Reactive Forms2</label>
  <app-switch id="switch-2" [value]="switchControl.value" [formControl]="switchControl"></app-switch>

  <hr />
  <button>Submit</button>

  <br />
  <h2>Form value</h2>
  {{ myForm.value | json }}
</form>

View Live Working Demo

If you want to learn more about syncing multiple reactive form inputs in Angular, check out this informative article by Corylan.

Answer №2

For me personally, I prefer not to use [value] and formControl in the same tag. Instead, another option is to utilize ngModel for one of the "inputs"

  <app-switch id="switch-2" 
         [ngModel]="myForm.value.mySwitch" 
         (ngModelChange)="myForm.get('mySwitch').setValue($event)"
         [ngModelOptions]="{standalone:true}">
  </app-switch>

Keep in mind that having the same FormControl in two different inputs is a common scenario - it's not exclusive to your custom form control.

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

What is the best way to standardize complex nested data within the ngrx/store?

Currently, I am utilizing ngrx/store with Angular 6. Within the store, there exists a deeply nested structure which I have concerns about in terms of its organization: const state = [ { aliases: ['alias1', 'alias2'], isRequir ...

The @angular/fire package is unable to locate the AngularFireModule and AngularFireDatabaseModule modules

I am facing some challenges while trying to integrate Firebase Realtime Database into my Angular project. Specifically, I am encountering difficulties at the initial step of importing AngularFireModule and AngularFireDatabaseModule. To be more specific, I ...

Different ways to pass a component function's return value to a service in Angular

On my HTML page, I am presenting job details within Bootstrap panels sourced from a JSON array using an ngFor loop. Each panel showcases specific job information along with a unique job ID. The panel is equipped with a click event which triggers the execut ...

Adding TH into a TABLE in Angular 2 by verifying TD elements

I am seeking a way to automatically generate thead and th, using td in the template : <Datatable> <tr #lineSelected *ngFor="let subscription of results"> <td nameColumn="Nom">{{subscription.name}}</td> <td n ...

steps to determine if a page is being refreshed

Is there a way to prevent the page from reloading when the user clicks the reload button in the browser? I attempted to use this code, but my break point is not triggering. ngOnInit() { this.router .events .subscribe((e: RouterEvent) = ...

Unraveling nested elements with the array map() method in Angular2 and Typescript: Fixing the issue of undefined property reference while mapping

Hey there! I'm currently working with Angular 4 and I have a piece of code that parses data from an API into a TypeScript array of rows. It's important to note that the code functions properly if elements like 'item.tceCampRun' and &apo ...

Trigger the ngOnInit() function of the app component for a second time by clicking on a link

Currently, I am in the process of restructuring an Angular project and came across the following functionality. Inside app.component.ts file ngOnInit() { this.portfolioID = Number(sessionStorage.getItem('portfolioID')); console.log(this.portfol ...

Toggle visibility of an Angular 4 component based on the current route

Hello there, I'm facing an issue and not sure if it's possible to resolve. Essentially, I am looking to display a component only when the route matches a certain condition, and hide another component when the route matches a different condition. ...

Refresh Angular component upon navigation

I have set up routes for my module: const routes: Routes = [ { path: ":level1/:level2/:level3", component: CategoriesComponent }, { path: ":level1/:level2", component: CategoriesComponent}, { path: ":level1", component: ...

Manually initiating event broadcasts in Angular 5

After researching, I discovered a solution for implementing $broadcast and $on in Angular 5. It involves creating a custom service called broadcaster. I have two parallel components that need to listen for change events triggered by the parent component. ...

What is the best way to send a list of data as either strings or integers through a REST API using Angular's

While trying to post data from Angular formData to a Django REST API, I encountered an error saying "Incorrect type. Expected pk value, received str." Here is how I am currently sending the data using form data: let noticeData = this.announceForm.value; i ...

Angular Universal: Execution of ngAfterViewInit occurring on the server side rather than the client side

While working on my server-rendered Angular application with Angular 17, I ran into a curious issue revolving around the ngAfterViewInit lifecycle hook. The situation arises when I call an init function within ngAfterViewInit, which relies on an API reques ...

Is it possible to configure a custom timezone for the Angular Material datepicker feature?

I am currently working on an Angular 7 application and I have encountered a challenge with the date field. In this particular field, I am utilizing the Angular Material Datepicker input. However, I have noticed that the datepicker automatically captures th ...

The TypeScript error message states, "The property 'breadcrumb' is not found within the type 'Data'."

My Breadcrumb Component is functioning properly when compiled to JavaScript and displaying the desired output. However, my IDE is showing an error message that I am struggling to fix. The error states: [ts] Property 'breadcrumb' does not exist o ...

Encountering difficulties in setting up ng zorro using Angular CLI for installation

I'm facing an issue with installing ng-zorro. Every time I try to run the command ng add ng-zorro-antd, I encounter an error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/c ...

Struggles with updating app.component.ts in both @angular/router and nativescript-angular/router versions

I have been attempting to update my NativeScript application, and I am facing challenges with the new routing system introduced in the latest Angular upgrade. In my package.json file, my dependency was: "@angular/router": "3.0.0-beta.2" After the upg ...

Access the $event object from an Angular template selector

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <input type="file" #myFile multiple /> <button (click)="onDelete(myFile.event)">DeleteFiles</button> My code snippet is experienci ...

The ASP.NET Core 3.0 Web API method consistently encounters null values

I've encountered an issue with my Angular app where it displays a 500 server error. Here are the methods I'm using: /*Product Service*/ addNewProduct(newProduct: Product): Observable<Product> { console.log(newProduct); return this.http.po ...

What are the steps to reduce the node version?

How can I downgrade my npm version from 16.13.1 to 12.0.1? Any guidance would be greatly appreciated! Thank you in advance. ...

Encountering problem while upgrading Angular Material from version 13 to 14 - error TS2307: Module '@angular/material/core/common-behaviors/constructor' not found

While upgrading Angular and Angular Material from version 13.2.6 to 14.2.2, I encountered the following challenges: Error TS2307: Module '@angular/material/core/common-behaviors/constructor' or its type declarations cannot be found. Error TS2345 ...