Add one string to an existing array

I have a component named ContactUpdater that appears in a dialog window. This component is responsible for displaying the injected object and executing a PUT operation on that injected object. The code for the component is shown below:

HTML

<form [formGroup]="updateForm">
    <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 Address"  formControlName="Email">
        <mat-error *ngIf="updateForm.controls.email.hasError('email')>
             Please enter a valid email address
        </mat-error>
    </mat-form-field>
    <button mat-flat-button (click)="onClick()">Save</button>
</form>

TS

import { Component, Inject,  OnInit} from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';
import {MAT_DIALOG_DATA, MatDialog, MatDialogRef, } from '@angular/material';
import { IContact } from 'src/app/models';
import { MyService } from 'src/app/services/my.service';

@Component({
  selector: 'app-update-contact',
  templateUrl: './update-contact.component.html',
  styleUrls: ['./update-contact.component.scss'],
})
export class UpdateContactComponent implements OnInit {
  public updateForm: FormGroup;
  public someContact: IContact

  constructor(@Inject(MAT_DIALOG_DATA) public data: IContact ,
              private fb: FormBuilder,
              public dialog: MatDialog,
              public myService: MyService,
              ) {} 

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

  public onClick() {
    this.someContact= this.updateForm.value;
    this.someContact.EMailAddresses = [];
    this.someContact.EMailAddresses.push(this.updateForm.value.Email);  
    this.myService.updateContact(this.someContact, this.someContact.Id);
  }

}

Contact JSON

{
  "Id": "",
  "Name": "",
  "EMailAddresses": [""],
},

Services file

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import {IContact } from 'src/app/models';

@Injectable({
  providedIn: 'root',
})

export class MyService {

 private  baseUrl : string = '......api Url.....';

 constructor(private http: HttpClient) {
}

public  updateContact(Id : string): Observable<object> {
  const apiUrl: string = `${this.baseUrl}/contacts/${Id}`;

  return this.http.put(apiUrl, contact);
}

}

When clicking the SAVE button without making any changes to the Email input field, I encounter an issue while trying to execute the PUT operation and receive the following error message.

https://i.stack.imgur.com/SFdiQ.png

Answer №1

The issue has been successfully resolved. Since the property EMailAddresses is stored as an array, it simply needs to be converted to a string and assigned to a single variable like so:

Typescript Code

public mail: string = this.data.EMailAddresses.toString();

and then displayed in the template as shown below:

HTML Code

<mat-form-field>
         <input matInput [(ngModel)]="mail"  placeholder="Email Address"  formControlName="Email">
 </mat-form-field>

Simply replace

[(ngModel)]="data.EMailAddresses"
with the new variable name.

Answer №2

There is a Syntactical Error in the initialization of the form:

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

In the "Email" form control, a Square Bracket is missing!

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

Getting the full referrer URL can be achieved by using various methods depending

I am currently working with ASP.Net. My goal is to retrieve the complete referrer URL when visitors arrive at my website from: https://www.google.co.il/webhp?sourceid=chrome-instant&rlz=1C1CHEU_iwIL457IL457&ion=1&espv=2&ie=UTF-8#q=%D7%90 ...

When a StaticFiles instance is mounted, FastAPI will issue a 405 Method Not Allowed response

Running a FastAPI application has been smooth sailing until I encountered an issue. In my current setup, the application script is as follows: import uvicorn from fastapi import FastAPI from starlette.responses import FileResponse app = FastAPI() @app.ge ...

What causes the lack of impact on lambda rendering speed despite integrating webpack?

Hey there, I've been working on implementing webpack for a project that involves microservices, Node.js, TypeScript, AWS, and AWS SAM. My main objectives are: Reduce the cold start time of lambda functions. Minimize security vulnerabilities by e ...

Incorporating dynamic form elements using Vue.js within a targeted div

Here is the HTML and Vue.js code that I have: <table class="table"> <thead> <tr> <td><strong>Title</strong></td> <td><strong>Description< ...

Issues with hover functionality in Javascript, CSS, and HTML

Seeking assistance with my JavaScript, HTML, and CSS development, I ran into an issue while trying to create a hovering function for my webpage. Despite my efforts, the links are not displaying anything when hovered over, and the divs meant for specific ho ...

Utilize Set.Attribute prior to entering the for loop

Could someone please clarify why I am unable to declare the var node before the for loop and then simply use appendChild(node) inside the loop? Why is it necessary to declare it for each iteration in order for it to affect all div elements? Otherwise, it w ...

The most lightweight scraper for individual website pages

There is a certain website that constantly updates its data. Unfortunately, there is no API available to access this information programmatically in JavaScript, which presents a common challenge for me. To tackle this issue, I have created a simple JavaSc ...

Error in Typescript for a function that accepts several types of lists - property does not exist on the interface

In my project, I have defined three interfaces: a base interface and two others that extend the base one with children as properties. One of the interfaces includes 'valueType' while the other includes 'returnType'. Here is how they are ...

The exportAs attribute is not specified as "ngForm" for any directive

Encountered an error while attempting to test the LoginComponent PhantomJS 2.1.1 (Linux 0.0.0): Executed 3 of 55 (1 FAILED) (0 secs / 0.307 secs) PhantomJS 2.1.1 (Linux 0.0.0) LoginComponent should create FAILED Failed: Uncaught (in promise): Error: Templ ...

What is the best way to retrieve the Axios Post response in React?

I'm facing a small issue. In my ReactJS code, I have a post function that is functioning correctly. However, I want to access the response of this function outside its scope, right where I called it. Is there a way to achieve this? async function che ...

Manipulating dynamic elements using jQuery

I am facing an issue with manipulating a dynamically created element using jquery fonticonpicker. Even though I have tried to modify the icon using the code below, it has not been successful as .icons-selector i is generated by the plugin itself. In the p ...

The Node JS API remains unresponsive when the request parameters are increased, continuing to send multiple requests to the server without receiving

Using the API below returns nothing: http://localhost:6150/api/v1/simpleSurveyData/abc/:projectId/:startDate/:endDate/:visitMonth However, if I remove any of the four parameters or provide less than four parameters, and adjust the API route in Node.js acc ...

A step-by-step guide on leveraging swagger-autogen in TypeScript applications

Is it possible to integrate the swagger-autogen module into a Typescript project? I have attempted multiple methods, but have been unsuccessful. The error message "Failed" keeps appearing when using a swagger.js file: const swaggerAutogen = require("swagge ...

Differences in file loading in Node.js: comparing the use of .load versus command-line

Currently, I am in the process of developing a basic server using vanilla JavaScript and Node.js. For this purpose, I have created a file named database.js, which includes abstractions for database interactions (specifically with redis). One of my objecti ...

Changes to the value of an Angular FormControl will automatically trigger changes in the entire formgroup

When attempting to validate the uniqueness of a user's email through an API call, I encountered a problem where any changes in form controls would trigger the value change. Below is my code: Errors(){ this.form01.valueChanges .subscribe((changed ...

Utilizing props to transfer data between components in ReactJS

I have a React application where I am binding text values when a specific div is clicked. However, I am now faced with the challenge of passing these text values to another component using props. This is what my code looks like: class PostOptionBar exten ...

Typescript: issue with type guard functionality not functioning properly

type VEvent = { type: "VEVENT"; summary: string; }; type VCalendar = { type: "VCALENDAR"; }; const data: Record<string, VEvent | VCalendar> = (...); array.map((id) => { return { id, title: dat ...

What is the reason the 'Add' type does not meet the 'number' constraint?

I experimented with type gymnastics using Typescript, focusing on implementing mathematical operations with numeric literals. First, I created the BuildArray type: type BuildArray< Length extends number, Ele = unknown, Arr extends unknown ...

Dynamic scrolling text for overflowing text display

Here's a scenario I'm facing: Let's say I have three div tags, each 100 pixels wide: <--- DIV WIDTH ---> Text in div 1 Text in div two, it overflows Text in div three <--- DIV WIDTH ---> Currently, I've set the following C ...

reading an array of objects using typescript

Trying to retrieve an object from an array called pVal. pVal is the array that includes objects. I am attempting to obtain the value of "group" based on the id provided. For instance, if the id is equal to 1, it should display "VKC". Any assistance woul ...