Bidirectional data binding in angular 12 reactive forms

After working with angular for a while, I encountered an issue while trying to implement two-way binding. The code snippet below is where I'm facing difficulty.

Since the use of [(ngModel)] has been deprecated in Angular 12 within formGroup, finding a solution has become challenging.

socials = [
{ name: 'Facebook', icon: 'facebook.webp', selected: false, link:'' },
{ name: 'Instagram', icon: 'instagram.webp', selected: false, link:'' },
{ name: 'Twitter', icon: 'linkdin.webp', selected: false, link:'' },
{ name: 'Whatsapp', icon: 'whatsapp.webp', selected: false, link:'' }

];

The goal here is to update the value of the link entered in the input field (6th last line).

<div class="row">
        <div class="col-6 col-lg-3 my-2" *ngFor="let control of socialsArray.controls; let i = index;">
          <input class="form-check-input" type="checkbox" (change)="getSelectedSocialsCards()" [formControl]="control" id="checkbox{{i}}">
          <label for="checkbox{{i}}" class="w-100">
            <div class="card cursorIn" [ngStyle] = "{'background-color' : socials[i].selected == true ? '#ededed' : '#fff'}">
              <div class="d-flex justify-content-end pt-2 pr-2 h-25">
                <fa-icon [icon]="faCheckCircle" [ngClass]="socials[i].selected === true ? 'iconColor' : 'iconColor1'"></fa-icon>
              </div>
              <div class="card-body d-flex p-0 px-4 mt-0">
                <div class="col-3 align-self-center font-weight-bold text-center cardIcon p-0">
                  <img src="/assets/images/social_media/{{socials[i].icon}}" width="40px" height="40px"
                    class="rounded-circle">
                </div>
                <div class="col-9 d-flex flex-column justify-content-start align-items-start cardRight">
                  <div>
                    {{socials[i].name}}
                  </div>
                </div>
              </div>
            </div>
            <div class="col-12 mt-2" [ngStyle] = "{'display' : socials[i].selected == true ? 'block' : 'none' }">
              <div class="form-group">
                <label>
                  {{socials[i].name}} link
                </label>
                <input type="text" class="form-control" (change)="getSelectedSocialsCards()" formControlName="socialLink">
              </div>
            </div>
          </label>
        </div>
      </div>

I've initialized socialLink inside formGroup.

socialLink: new FormControl(null, [Validators.required])

This is the corresponding code from my component.ts file:

getSelectedSocialsCards() {
this.selectedSocialsCards = [];
this.socialsArray.controls.forEach((control, i) => {
  this.socials[i].selected = false;
  if (control.value) {
    this.socials[i].selected = true;
    this.socials[i].link = this.addForm.get('socialLink').value;
   let linksValue = {'socialName': this.socials[i].name, 'socialLink': this.socials[i].link}
    this.selectedSocialsCards.push(linksValue);
  }
});
console.log(this.selectedSocialsCards);
this.socialError =  this.selectedSocialsCards.length > 0 ? false : true;
this.addForm.patchValue({socialsCheck: this.selectedSocialsCards});

}

Currently, I can only retrieve the latest value inserted into the input field and it applies to all the links.

I've made various attempts to resolve the issue but haven't found a solution yet. Any assistance on this matter would be greatly appreciated. Thank you

Answer №1

To utilize [(ngModel)] within a formGroup, include 'name' in the tag. For instance, <input class="form-check-input" type="checkbox" (change)="getSelectedSocialsCards()" [formControl]="control" [(ngModel)]="testcontrol" name="testcontrol" id="checkbox{{i}}"> like that

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

Problems with the Chosen property of MenuItem within Material-UI

The MenuItem's "selected" property does not seem to be functioning correctly within the Select component. For reference, please visit https://codesandbox.io/s/9j8z661lny I have attempted to use comparison with the Id, and even tried using selected={t ...

Node.js Export Module Error - importance of separating concerns

I have been attempting to implement separation of concerns by using export module. Everything functions properly when used without separating concerns, but as soon as I try to import generateUrlArray() from const db = require('../db'), nothing se ...

Ways to provide input parameters to a method upon clicking an element without using the HTML onclick attribute

Is there a way to pass data between pages without redirecting to the next.php page every time a button is clicked? One suggestion is to remove the onclick attribute from the button: <button class="submit-btn"></button> and use this jQuery fu ...

Having some issues with validating numbers in typescript

When implementing react hook form in my React app, I encountered an issue while validating specific fields and had to add some conditions to the schema. yup .object({ test1: yup.number().when('test2', (test2: number, schema: yup.NumberSchem ...

Apollo useQuery enables risky array destructuring of a tuple element containing any value

Currently, I am incorporating TypeScript into my project and have a GraphQL query definition that utilizes Apollo's useQuery. According to the documentation, the call should be typed, however, I am encountering an ESLint error regarding data being ass ...

Is the window frozen while Ajax processes the request?

When I make an ajax request that may take a significant amount of time to process on the server-side, I want to display a loading image during the request. However, the loading image is not showing up while the ajax request is processing. var ref = create ...

The error message "TypeError: addNewUser is not a function in React.js onSubmit

What could be causing the error message "TypeError: addNewUser is not a function"? The issue arises when I complete the form and click save, displaying the error that addNewUser is not defined as a function. The problem occurs within the following code ...

Prevent Click Event in JQuery

I have a requirement to disable all click events on my webpage. However, even after using the appropriate code to prevent these events from firing, some of them are still getting called. Let me explain with an example. <div id='parent'> ...

Achieving a persistent footer at the bottom of the page within Material Angular's mat-sidenav-container while using the router-outlet

I am looking to keep my ngx-audio-player fixed at the bottom of the screen, similar to what you see on most music streaming websites. I currently have a structure with divs and various elements for dynamic content and playing music. The issue is that the ...

Tips for implementing code to function across several images in HTML and CSS

Hey there, I'm currently working on a website project for my friend and I sometimes refer to www.w3schools.com for help with coding. I'm having trouble implementing a gallery feature where users can click on images to view them fullscreen. I foun ...

Navigating through async functions in an Express.js router

Encountered a lint error indicating that Promises cannot be returned in places where a void is expected. Both functions [validateJWT, getUser] are async functions. Any suggestions on how to resolve this issue without compromising the linter guidelines by u ...

Utilizing JSON and CodeIgniter within HTML elements

I am interested in creating a private chatroom using CodeIgniter and JSON format. I want the JSON data retrieved to be displayed in a list structure like <ul><li>messageinJSON</li></ul>. This formatting will allow me to customize th ...

What happens when there is no match found while attempting to edit a form with the UI-Bootstrap typeahead directive?

Here is the code that demonstrates how my typeahead input box functions. Users can enter a name, and the relevant information will populate the rest of the form. If no match is found, users should still be able to input the name and related details into th ...

Struggling to implement the proper authentication method with API in Ionic

Having an API for the login, but being new to Ionic is causing difficulty in creating the correct method for the login process. The service file is located here: providers/restapi/restapi.ts import { HttpClient } from '@angular/common/http'; im ...

Creating a worldwide object in JavaScript

I am trying to create a global object in JavaScript. Below is an example code snippet: function main() { window.example { sky: "clear", money: "green", dollars: 3000 } } However, I am unable to access the object outside th ...

Refining information and displaying it alongside the "indelible" data - react

I recently implemented a TextField component from the MUI library, along with a useRef hook to capture user input "live" as they type. The goal is to filter rates based on the characters entered by the user. Currently, I am working with an array of rate ke ...

Refine your search with a JSON object description in expressJS and UnderscoreJS

[ { "id": 1, "description": "Empty the garbage bin", "completed": false }, { "id": 2, "description": "Dine out for dinner", "completed": false }, { "id": 3, "description": "Exercise at the fitness center", "com ...

Create a package themed with Material UI for export

I am attempting to create a new npm package that exports all @material-ui/core components with my own theme. I am currently using TypeScript and Rollup, but encountering difficulties. Here is the code I have: index.ts export { Button } from '@materia ...

angular2 utilize rxjs to search for threads based on user input

Hey there! I'm working on creating a mini forum inspired by stackoverflow and I'm currently in the process of adding a basic text filter for thread titles. I've recently delved into rxjs and pipes, and this is what I've come up with so ...

What is the method for launching Chrome synchronously in Selenium WebDriver using createSession()?

After executing the code below using Selenium WebDriver to launch a Chrome browser: import { Driver } from 'selenium-webdriver/chrome'; Driver.createSession(); console.log("I've launched!"); I'm encountering an issue where "I've ...