Send empty object using FormBuilder

When retrieving an object from a backend API service like this:

data: {firstName:'pepe',lastName:'test', address = {street: 'Cervantes', city:'Villajoyosa'} }
or data: {firstName:'pepe',lastName:'test', address = null }

I am facing an issue where I need to set the object in the formGroup. However, when the address is null, I want to save it as null instead of {street: '', city:''}}

     form = this.fb.group({
            firstName: [''],
            lastName: [''],
            address: this.fb.group({
              street: [''],
              city: [''],
            }),
          });
    // setting the form:
    if(data.address)
    this.form.controls['address'].setValue(data.address)
save(){
valueToSend = this.form.controls['address'].getValue()
}
// template
<button (click)=save()>Save</button>
    <div formGroupName="address">
      <h3>Address</h3>
      <label>
        Street:
        <input type="text" formControlName="street">
      </label>
      <label>
        City:
        <input type="text" formControlName="city">
      </label>
    </div>

Answer №1

Before focusing on the form, make sure to save your data first. During submission process

save()
{
  const data={...this.form.value,address:...this.form.value.address} //<--creating a duplicate
  if (!data.address.city && !data.address.street)
  {
       data.address=null;
  }
  ..perform an action with the data..
  myService.update(data)
}

Answer №2

If you've defined a specific form structure, you're constrained to it and may need transformation logic when submitting the form.

One way to handle this is by extracting data from the form fields upon submission:

const { firstName, lastName, address } = this.form;
const value = {
    firstName,
    lastName,
    address: address.street || address.city ? address : null
};

Alternatively, you can create a component that utilizes ControlValueAccessor for this purpose, as shown below:

@Component({
  selector: "app-address",
  template: `
    <div [formGroup]="form">
      <input formControlName="street" />
      <input formControlName="city" />
    </div>
  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => AddressComponent),
      multi: true
    }
  ]
})
export class AddressComponent implements ControlValueAccessor, OnInit {
  form: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.form = this.fb.group({
      street: [""],
      city: [""]
    });
  }

  writeValue(obj: any): void {
    this.form.setValue(obj);
  }

  registerOnChange(fn: any): void {
    this.form.valueChanges.pipe(map(x => x.city || x.street ? x : null)).subscribe(fn);
  }

  registerOnTouched(fn: any): void {
    //TODO
  }

  setDisabledState(isDisabled: boolean): void {
    //TODO
  }
}

Try out the live demo on Stackblitz

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

Creating and verifying variables in a template

I'm currently exploring how to assign a variable when a specific value/string is identified in an ngFor loop, and then exhibit a div within the same template upon identification... When the condition indicated in the code snippet below holds true, I ...

Enhance the efficiency of writing the *.d.ts file

I have recently started diving into TypeScript with React and encountered a new concept called a .d.ts file. I am wondering if there is an established best practice for writing this file or if it's more of a developer preference. Can someone verify if ...

What is the best method for accessing the properties of a JavaScript object based on input from a textbox?

Just starting out with angular and having trouble generating or updating a table based on text boxes. The schema includes country, sales, and profit fields. There are two text boxes for the x-axis and y-axis inputs. The table should dynamically update when ...

Initialization issue detected in Angular's module APP_INITIALIZER

In my auth module, I have implemented a mechanism to import and set up MSAL configuration before initializing the app. I am using APP_INITIALIZER to delay the initialization of the app until the configuration for MSAL-ANGULAR is retrieved. The issue I am f ...

Issues with the inheritance functionality in styled components are causing errors

The issue arises when I try to customize the styling of my PrimaryButton component, separate from the DefaultButton. Despite writing style properties for it, the changes do not take effect. Here is the folder structure: https://i.stack.imgur.com/0KjyH.pn ...

What is the best way to combine two calls into a single condition check in React using Typescript?

Does anyone have suggestions on how to tackle this issue? I'm encountering difficulty as it is contained within a tag, which means it adheres to specific rules that I am unfamiliar with. The task involves generating a graph, and when the expandGraph v ...

Is it possible to include multiple eventTypes in a single function call?

I have created a function in my service which looks like this: public refresh(area: string) { this.eventEmitter.emit({ area }); } The area parameter is used to update all child components when triggered by a click event in the parent. // Child Comp ...

Create a Typescript type extension specifically designed for objects with nested arrays of objects

After stumbling upon this inquiry, I am eager to adjust my code in a similar fashion, utilizing typescript and a more intricate object. Consider the type below: export type ImportationType = { commercialImportation: boolean dateToManufacturer: string ...

What are the best techniques for centering a prime ng form both vertically and horizontally?

I am currently using prime ng 9.1.3 along with primeflex 1.3.0 in my project. Despite applying p-align-center, I am facing difficulty in vertically and horizontally centering the form on the screen when using a full screen height of 100vh. <div class=&q ...

Issues with relocating function during the NgOnInit lifecycle hook in an Angular 2 application

Currently, I am facing an issue with my Angular 2 app where the data sometimes lags in populating, causing a page component to load before the information is ready to display. When this happens, I can manually refresh the page for the data to appear correc ...

The most secure method for retrieving User Id in AngularFire2

I'm currently facing a dilemma in determining the most secure method to obtain an authenticated user's uid using AngularFire2. There seem to be two viable approaches available, but I am uncertain about which one offers the best security measures ...

Unable to reach the exposed port of the container

I am having difficulty accessing an Angular application that I have deployed within a container. Despite exposing the port in my Dockerfile and mapping the port in the docker-compose file, I still cannot access it from my web browser (Mozilla). There are ...

Is there a method to accurately pinpoint the specific type?

Is there a way to optimize the validateField function to narrow down the type more effectively? type TStringValidator = (v: string) => void; type TNumberValidator = (v: number) => void; type TFields = 'inn' | 'amount'; interface ...

Encountering the error message "The argument type 'AsyncThunkAction<*>' cannot be assigned to the parameter type 'Action<any>'" while trying to utilize a custom typed useAppDispatch hook

For a live example, you can check out this link. In the process of developing a React application with TypeScript and Redux Toolkit, I have meticulously followed the guidelines outlined in the documentation. As a result, I have successfully implemented ty ...

Implementing strict validation for Angular @Input by allowing only predefined values

I am facing an issue where I receive a string value as a parameter in a component, but I want to restrict the possible values that can be passed as a parameter, similar to using an enum. Currently, I have: @Input() type: string = ''; However, ...

There was an error in parsing the module: an unexpected token was encountered during the rendering

Recently, I've been working on configuring React with Typescript (for type checking), Babel for code transpilation, Jest for testing, ESLint for code checking, and a few other tools. You can find all the necessary files in the repository linked below. ...

"Troubleshooting asynchronous requests in Angular and the issue with Http.get method

I have encountered an issue with my code while trying to make a http request to obtain the client's geoLocation and sending it to my API using http.get as a parameter. Although I have successfully implemented both functionalities, I am facing challeng ...

What is the correct way to properly parse JSON attributes containing slashes?

I have 2 Custom Interfaces: DataModel.ts export interface Entry{ id: number, content: Note } export interface Note{ message: string } These interfaces are utilized in typing the HttpClient get request to fetch an array of Entries: DataService.ts getE ...

"Encountering a problem during the installation of the Angular

After investing numerous hours, I am still unable to identify the issue with running an angular based project. node version: v12.16.1 I executed npm install -g @angular/[email protected] However, upon entering the command ng build --prod, I enco ...

Display of environment variables in the production build

In a nutshell, I somehow "downloaded" my app (Ctrl+S or right click+save as) and discovered that my environment variables are not hidden but stored in a file named main.xxxx.js (where xxx is the build hash). I came across a secret key for a service in tha ...