Incapable of adding a singular string to an array without altering the string's original value

Introducing the edit-customer component, a dialog window designed to receive an injected object from another component and display its properties, such as name and email. Below is the code for this component:

HTML

<form [formGroup]="editForm">
    <mat-form-field >
        <input matInput [(ngModel)]="data.name"   placeholder="Name"  formControlName="name" >
    </mat-form-field>
    <mat-form-field >
        <input matInput [(ngModel)]="data.EMailAddresses"   placeholder="Email Id"  formControlName="email" >
    </mat-form-field>
      <button mat-flat-button (click)="onEdit()">Save</button>
</form>

TS

import {Component, Inject,  OnInit } from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';
import { IContact } from 'src/app/models/app.models';
import { CustomersService } from 'src/app/services/customers.service';

@Component({
  selector: 'atd-edit-customer',
  templateUrl: './edit-customer.component.html',
  styleUrls: ['./edit-customer.component.scss'],
})
export class EditCustomerComponent implements OnInit {
  public editForm: FormGroup;
  public someContact: IContact; 

  constructor(@Inject(MAT_DIALOG_DATA) public data: IContact,
              private fb: FormBuilder,
              public customersService: CustomersService,
              ) {} 

  public ngOnInit(): void {
    this.editForm = this.fb.group({
      name: [null],
      email: [null,[Validators.email],
    });
  }

  public onEdit(): void {
    this.someContact = this.editForm.value;
    this.someContact.EMailAddresses= [];
    this.someContact.EMailAddresses.push(this.editForm.value.email); 
    this.customersService.updateContact(this.someContact);
  }
}

JSON looks like this:

export interface IContact {
  id:       string;
  name:     string
  emailId:  string[];
}

The Current Issue:

  • Upon hitting the SAVE button without changing the email input field, the PUT operation fails with this response:

https://i.sstatic.net/Q3uCc.png

  • However, if changes are made to the email input field before saving, the PUT operation completes successfully.

The email address is being updated using the following code:

this.someContact.EMailAddresses= [];
this.someContact.EMailAddresses.push(this.editForm.value.email); 

What could be causing this issue?

Answer №1

It seems like your question needs some clarification.

From what I gather, the issue arises when the user clicks on the save button without making any changes.

To address this problem, avoid using both ngModel and formControlName simultaneously; choose one for each element.

What exactly is happening in your situation?

If you set the default value of the email control to null, it will remain empty until a new value is provided through ngModel.

But why do I see a value then?

The value displayed comes from ngModel, not directly from the control itself.

Try modifying your code as follows:

public ngOnInit(): void {
    this.editForm = this.fb.group({
        name: [this.data.name],
        email: [this.data.email, Validators.email],
    });
}

Make sure to eliminate the use of ngModel on the form fields.

By the way, combining ngModel with formControlName may lead to errors in newer versions of Angular.

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

Can you guide me on how to specify the return type in NestJS for the Session User in a request?

async authenticated(@Req() request: Request) { const user = request.user return user } It is important for the 'user' variable to have the correct type globally. While working with express passport, I came across the following: decl ...

What is the best way to troubleshoot the type of data being sent to the subscriber of an Angular observable?

I am new to the world of Angular-7, RxJS-6, and Visual Studio Code. Currently, I am facing a challenge with debugging an Observable that is being returned to a subscriber, resulting in a "TypeError" at runtime. It seems like this issue is not uncommon amon ...

How can I incorporate an iframe into Angular while utilizing a value fetched from MongoDB as the src attribute?

When using an iframe similar to this: <iframe class="e2e-iframe-trusted-src" height="480" width="500" src={{trailer.address}}> </iframe> I encountered the following error: "ERROR Error: unsafe value used in ...

Issue with for loop execution within subscribe event

In my chat design, there is a list of people on the left side. When a user clicks on any person, I display their chat history on the right side. To achieve this, I need to transfer user details from one component to another using an RXJS subscribe call. Da ...

What is the reason for the continual appearance of the *ngIf validation message?

Currently, I am working with Angular and HTML. I have implemented pattern validation for the first name field, which should not accept only numbers. <fieldset class="six"> <input id="firstName" ng-pattern="^[a-zA-Z]+$" type="text" ...

Vue's span function is yielding the promise object

In my Vue component, I am using the function getOrderCount to fetch the number of orders from a specific URL and display it in one of the table columns. <div v-html="getOrderCount(user.orders_url)"></div> async getOrderCount(link) { ...

"Troubleshooting: Issues arise with Kendo UI Angular file upload component when dealing with

Currently, I have integrated the Kendo Angular File Upload component into my Angular 7 application. The backend of this application is built using ASP.NET Core 2.1 and hosts a MVC API through Kestrel. While the file uploads for smaller files are successful ...

Using React to update the state of an array of objects

I'm faced with a challenge in changing the properties of an object within an array of objects at a specific index using a function: const handleEdit= (index) =>{ if(itemList[index].edit==true){ const copied=[...itemList]; const item2 = {...ite ...

Creating a dynamic image binding feature in Angular 8

I am working with an object array that requires me to dynamically add an image icon based on the type of credit card. Typescript file icon: any; savedCreditCard = [ { cardExpiryDateFormat: "05/xx", cardNumberLast: "00xx", cardId: "x ...

Angular NgFor directive for rendering data

Is it possible to showcase information from a selected *ngFor on another page? For instance, I have two pages: result.component.html and details.component.html result.component displays data using *ngFor while details.component showcases the details of th ...

Using Tomcat as the backend server, Angular as the frontend framework, and

I am facing difficulties in consuming a tomcat POST service using an Angular front end. As I am relatively new to Angular, I may need some guidance. Here is my current environment: Tomcat 9.0 JDK 17 Angular 17 with standalone components javax.ws.rs framew ...

When the file is active on a local machine, the bot commands run smoothly. However, these commands do not execute on a remote

Lately, while working on coding a discord bot using discord.js, I came across an issue. Whenever I run my bot on my local machine, all the commands work perfectly fine. However, after committing and pushing the code to GitHub, and then allowing buddy.works ...

When utilized in a nested component, the service is found to be null

When developing a nested component, I encounter an issue where the injected service is null. How can I successfully use a service in a nested component? export class ActivityComponent implements OnInit { constructor( . . public accountServ ...

What is the best way to connect input values with ngFor and ngModel?

I am facing an issue with binding input values to a component in Angular. I have used ngFor on multiple inputs, but the input fields are not showing up, so I am unable to push the data to subQuestionsAnswertext. Here is the code snippet from app.component ...

Why aren't the validations being set when creating Angular forms using formControl.values?

I had to structure the form in a specific way in my app.ts file -> courseNameControl = new FormControl("", [Validators.required,Validators.minLength(2)]); contentControl = new FormControl("", Validators.required); form = { cours ...

Error message on Angular 4: "404 - Unable to locate file

Currently, I am working with Angular 4 and attempting to load .csv data. For reference, I have been following this guide: . However, I am facing issues while trying to load the sample.csv file. Despite trying to place the file in src/app, src, or root dire ...

Problem with lazy loading in Angular nested routing

My application requires the sign-in functionality to be available at startup, with all other code lazy loaded after authentication. I've set up a core module consisting of a core-routing module and a core component to manage this process. However, the ...

Implement Angular in a non-conventional Angular-based venture

Is there a way to incorporate Angular into a project that is built on a different framework? Specifically, I have a .NET MVC project that uses Razor for the markup. I want to make some ajax calls and update parts of the UI without using JQuery. Instead, I ...

Enhance your TypeScript React development with NeoVim

As a newcomer to vim, I decided to test my configuration with react and typescript. To do this, I created a simple demo app using the command npx create-react-app demo --template typescript. Next, I opened the directory in neovim by running nvim .. However ...

Angular 5 (ionic 3) does not support the FormControl debounceTime feature

Recently, I upgraded Angular in my Ionic app from version 4 to 5. In the app, I have search FormControl inputs that allow users to search a database through ajax requests. Previously, I used the debounceTime() method to delay the ajax search request. Howev ...