What is the process of including a new key and value in an Angular form group?

Is there a way to include the associatedAccount as both key and value in the formgroup, so that it is submitted along with the rest of the form data? Any suggestions would be greatly appreciated. Thank you.

Currently, I am planning to add the modelForm value to the post request using this.accountService.create(this.modelForm.value), but I also need to incorporate the value from the getAssociatedAccount request. Thank you for your help.

The associatedAccount value is not part of the Form itself, but I aim to include it in the formgroup as a single object.

Perhaps something like: associatedAccount: this.associatedAccount

#request

getAssociatedAccount() {
    this.isInProgress = true;
    this.userService.getUserProfile(this.authService.authUser.nameid)
      .pipe(
        finalize(() => this.isInProgress = false),
      ).subscribe({
        next: (res:any) => {
          if (res.isSuccess) {
            this.associatedAccount = res.data.associatedAccount
          }
        },
        error: err => noop,
        complete: () => noop
      });
  }

#model

private _createModelForm(): FormGroup {
    return this.formBuilder.group({
      // id: [this.model.id || 0],
      emailAddress: new FormControl(this.model.emailAddress, [
        Validators.required,
      ]),
      firstName: this.model.firstName,
      roleId: this.model.roleId,
      lastName: this.model.lastName,
      phoneNumber: this.model.phoneNumber,
      companyName: this.model.companyName,
      ssocredentials: this.model.ssocredentials,
      accountId: this.accountId,
      title: this.model.title,
      isSso: [this.model.isSso || []],
    });
  }

Answer №1

By incorporating the spread operator, you have the ability to introduce a new property during form submission without the need to add a new formControl.

submit(form)
{
   if (form.valid)
      this.accountService.create({
         ...form.value, //<--all the properties of form.value
         associatedAccount :this.associatedAccount //<--and another one
                    })
}

To enable editing capabilities, it is indeed possible to include a new control using the addControl method.

   this.form.addControl("associatedAccount",new FormControl(this.associatedAccount))

IMPORTANT: It's also feasible to initialize the form with this particular property and assign a value to it utilizing the setValue method (remember, a FormGroup can exist independently without an input control).

  this.form.get("associatedAccount").setValue(this.associateAccount)

IMPORTANT2: Additionally, within the service, prior to making the API call, you can retrieve the value before sending it.

create(data:any){
   this.userService.getUserProfile(this.authService.authUser.nameid)
      .pipe(
        switchMap(res=>{
          if (res.Success){
            const dataSend={...data,res.data.assocciatedAccount}
            return this.httpClient.post(".....",dataSend)
          }
          return of({Success:false,Error:"Can't get associatedAccount"})
        })
        finalize(() => this.isInProgress = false),
      ).subscribe()
}

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

Is there a way to determine if individuals in my contact list have installed and are using my app? Using Ionic 2

I need the following feature: When a user clicks on the contacts button, they should be able to view all contacts from their device who are currently using the app. Additionally, they should see an "invite" option for contacts who are not yet using the app ...

Is your Angular2 form page experiencing reloading issues?

I am currently incorporating Angular2 into my project. I am facing an issue where the page keeps refreshing, and I'm unable to determine the cause. Below is a snippet of my form: <form> <div class="form-group"> ...

Validation in Angular 2+ for child components

I am seeking assistance with Angular as I do not have expert knowledge in it. My goal is to implement form validation in a component named "viewForm". This form is created using an object array loop called "points". Towards the end of the "viewForm", I hav ...

The function `pickupStatus.emit` is not defined

Currently, I have a driver's provider that monitors changes in my firestore database and updates the status of a driver pickup request. Here is the function responsible for this process: getDriverPickupRequest(id) { this.DriverCollection.doc<Driv ...

mobile device experiencing issues with bootstrap d-flex alignment

I have a parent div with three nested divs structured like this: .button-class { margin-top: 0.5rem; margin-right: 0.5rem; margin-left: 45rem; } .svg-class { margin-top: 1rem; } <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/&l ...

Include links to external CSS and JS files within an Angular 2 component

To exclusively use "Bootstrap Select" in my.component.ts, I attempted the following approach: @Component({ templateUrl: 'my.component.html', styleUrls: [ 'my.component.css', //Bootstrap Select 'https:/ ...

Apply CSS styles conditionally to an Angular component

Depending on the variable value, I want to change the style of the p-autocomplete component. A toggle input determines whether the variable is true or false. <div class="switch-inner"> <p [ngClass]="{'businessG': !toggle }" clas ...

How can a button click function be triggered in another component?

These are the three components in my dashboard.html <top-nav></top-nav> <sidebar-cmp></sidebar-cmp> <section class="main-container" [ngClass]="{sidebarPushRight: isActive}"> <router-outlet></router-outlet> & ...

Tips on how to effectively unit test error scenarios when creating a DOM element using Angular

I designed a feature to insert a canonical tag. Here is the code for the feature: createLinkForCanonicalURL(tagData) { try { if (!tagData) { return; } const link: HTMLLinkElement = this.dom.createElement('link'); ...

Exploring the Power of Routing in Angular 4 and WordPress

I am encountering an issue with routing in my Angular 4 app within a Wordpress theme. Currently, the page resolves to: But I want it to resolve to: Any suggestions on how to solve this problem? ...

The custom FontAwesome icon is failing to display properly

UPDATE : Here is the StackBlitz as requested. A custom SVG icon was created based on instructions provided by FontAwesome's collaborator found here. Despite mirroring the exact element structure of FontAwesome's icons, the custom icon does not ...

Problem with Angular Slider

I'm in the process of creating a carousel component in Angular, but I'm facing an issue where the carousel is not appearing as it should. Below is the code for my carousel component. carousel.component.html: <div class="carousel"> ...

Issue TS2322 occurs when an element is not compatible with type ReactElement. Mysteriously, this error appears inconsistently within the application

I have successfully resolved the error mentioned, but I am seeking clarification on why it is occurring in this specific instance and not in other parts of my application. Additionally, I am curious as to why a function and a ternary with the same type sig ...

How can I create a sticky header and footer for an Angular UI Material table, while also ensuring that a common page header remains sticky?

Despite following the documentation for a sticky table header, I encountered an issue where setting the height of .example-container to 100% did not make the table's header stick as intended. table.component.html <div class="example-container ...

Traversal of a binary tree in the order of visitation specified by the In

My task was to create a function that traverses a binary tree and returns an array of all its values in inorder. The code provided is: interface BinTree { root: number; left?: BinTree; right?: BinTree; }; const TreeInArray =(t:BinTree):number[] =>{ ...

cycle through options of radio buttons

How can I display items of radio buttons, with the values of these items coming from a backend api? <div class="input-group col-md-9 input-group-sm"> <label>gender</label> </div> <!-- TO CORRECT ...

Simulating a continuous key press on the keyboard for 5 seconds with TestCafe

Despite my attempts to send it to the browser console by using .pressKey("PageDown") after tracking it, nothing seems to be happening. I'm at a loss on what steps to take next - perhaps there are some examples available? I was advised to uti ...

Encountering a snag when trying to start up the Angular application

When I try to start my Angular application using the command ng serve --port 4200 --host 127.0.0.1 --disable-host-check true --ssl true, I encounter the following problem: Error: Could not locate the '@angular-devkit/build-angular:dev-server' bui ...

methods for sharing real-time data between parent and child components in Angular versions 2 and above

When working with Angular, we are familiar with parent to child communication using the @Input decorator. However, the challenge arises when we need to pass dynamic data from the parent to the child component. Imagine having a 'name' property def ...

The process of Angular change detection refreshing the DOM

Exploring the Angular change detection process led me to observe some unusual behavior in the Chrome dev tools. To showcase this behavior, I created a plnkr: http://plnkr.co/edit/cTLF00nQdhVmkHYc8IOu The component view is quite simple: <li *ngFor="le ...