Exploring Angular 5: Working with Object-Based Form Controls

I am currently developing an Angular application with Django as the backend.

One of the features of my application is to show a list of members. The structure of the members array is as follows:

[
  {
    name: 'John Smith',
    id: 3,
    score_set: [...]
  },
  {
    name: 'Jane Doe',
    id: 7,
    score_set: [...]
  },
  {
    name: 'Bill Appleseed',
    id: 3,
    score_set: [...]
  },
  {
    name: 'Bob Lee',
    id: 3,
    score_set: [...]
  }
]

I have successfully implemented this feature, but now I need users to be able to edit the names of these members. I attempted to use Reactive Forms for this purpose:

Initially, I created a FormGroup that includes a single FormArray. This FormArray holds all the member objects:

this.form = this.fb.group({
  roster: this.fb.array(this.members.map((elem) => [elem, Validators.required]))
});

Next, I designed the template for the component:

<form>
  <div [formGroup]="form">
    <div formArrayName="roster">
      <div *ngFor="let control of form.controls.roster.controls">
        <div class="form-group">
          <input class="form-control" [formControl]="control" placeholder="Enter name">
        </div>
      </div>
    </div>
  </div>
</form>

However, instead of displaying just the name property of each member, it tries to display the entire object resulting in [Object object]. Is there a way to configure each FormControl to utilize the name property as its value?

I aim to only display the name in the <input> field and when the user edits it, the name property of the object should update while keeping all other properties intact.

Any assistance on this matter would be greatly appreciated!

Answer №1

To preserve the entire object, you will need to set up formGroups as shown below:

interface Member {
  id: number;
  name: string;
}

ngOnInit(): void {
  this.formGroup = this.formBuilder.group({
    roster: this.formBuilder.array(this.members.map(member => this.createMemberGroup(member))),
  });
}

createMemberGroup(member: Member): FormGroup {
  return this.formBuilder.group({
    ...member,
    name: [member.name, Validators.required],
  });
}

HTML:

<form class="container pt-2" [formGroup]="formGroup">
  <div formArrayName="roster">
    <div 
      [formGroupName]="index" 
      *ngFor="let control of formGroup.get('roster').controls; index as index">
      <div class="form-group">
        <input 
          class="form-control" 
          formControlName="name" 
          placeholder="Enter name" 
          [class.is-invalid]="control.invalid">
        <small class="text-danger" *ngIf="control.invalid">Required</small>
      </div>
    </div>
  </div>
</form>

DEMO

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

Stop access to specific pages or routes

I need help with restricting navigation in my Next.js app. While reading the documentation here, it mentions the importance of guarding against programmatically navigating to unwanted routes, but I'm unsure about how to implement this. Let's say ...

Filtering without the includes() Method

I have two Objects that are structured as follows: export const recipes: Recipe[] = [ new Recipe( id: "Green", scenario: ["1", "2"]), new Recipe( id: "Blue", scenario: ["1", "2","2"]) ]; export const scenarios: Scenario[] = [ new Scenario( id: "1 ...

In a Custom Next.js App component, React props do not cascade down

I recently developed a custom next.js App component as a class with the purpose of overriding the componentDidMount function to initialize Google Analytics. class MyApp extends App { async componentDidMount(): Promise<void> { await initia ...

Is there a way to retrieve data from Angular RC4 routing?

Within the app routes: { path: 'calculator', component: CalculatorComponent, data: {physical: Physical}}, In the settings component: if(this.selectedPhysical) { this.router.navigate(['/calculator', this.selectedPhysical ]); } ...

Adding color dynamically to text within ion-card based on a regex pattern

My goal is to enhance the appearance of certain text elements by wrapping them in a span tag whenever a # or a @ symbol is detected, creating the look of usernames and hashtags on Twitter. Below is the code I am currently using: TS FILE: ngOnInit(): void ...

The ng2 Bootstrap modal will not close unless the button has an onclick function attached to it

I have been working on creating a page that displays a list of items. Each item, when clicked, triggers a ng2-bootstrap modal to show detailed information about that specific item. However, I encountered an issue when attempting to use (click)="lgModal.sho ...

Using Jest and Supertest for mocking in a Typescript environment

I've been working on a mock test case using Jest in TypeScript, attempting to mock API calls with supertest. However, I'm having trouble retrieving a mocked response when using Axios in the login function. Despite trying to mock the Axios call, I ...

Setting a default value for a complex prop in Vue through Type-based props declarations

I'm struggling with this issue: Argument of type 'HelloWorldProps' is not assignable to parameter of type 'InferDefaults<LooseRequired<HelloWorldProps>>'. Types of property 'complexProp' are incompatible.ts( ...

The ability of Angular 4 ngComponentOutlet to load dynamic components is great, however, there seems to be an issue

Currently, I am faced with the challenge of loading various 'parent' components and injecting route content into these individual parent components by utilizing ng-content in each one. Essentially, the purpose of each parent component is to manag ...

Tips for combining Angular 2 with a current J2EE Spring project and deploying them on the same PORT

I currently have a project with Spring on the back-end and AngularJS 1 on the front-end. When I start the Spring server, it only opens one port for me: 8080 which allows me to access REST APIs and the AngularJS front-end components. https://i.stack.imgur. ...

Having trouble installing plugins on Ionic 6. Every time I try, an error pops up. Any suggestions on how to proceed?

Failed to fetch plugin https://github.com/katzer/cordova-plugin-background-mode.git via registry. It seems like there is a connection issue or the plugin specification is incorrect. Please check your connection, as well as the plugin nam ...

Combining Angular 2 and Sails.js for Ultimate Web Development

Looking to integrate Sails with Angular 2 and add TypeScript to my project. As a newcomer in this field, I'm unsure how to configure this. I have created a Sails app using the command: sails new myApp Could anyone guide me on how to incorporate thi ...

What are the best practices for passing the type of getServerSideProps to the page props in Next.js?

After discovering two working solutions, I am unsure which approach is more consistent. interface ICatalogHome { response: Result<CatalogHomePageResponse>; } export const getServerSideProps: GetServerSideProps<ICatalogHome> = async (contex ...

Executing "Ng build --watch" results in generating corrupt sourcemaps

Ever since upgrading to Angular 8, I've noticed some strange behavior with the ng build command. Initially, running ng build --watch stopped generating valid source maps that were recognized by the browser. Fortunately, I discovered that adding the - ...

Discovering the title of a page in layout using Nextjs 13

How do I extract the title stored in the metadata object within the layout.tsx file? page.tsx: import { Metadata } from 'next'; export const metadata: Metadata = { title: 'Next.js', }; export default function Page() { return &a ...

Utilizing the expression in *ngIf directive in Angular 2 allows for

Currently, I am exploring the possibility of utilizing a function's return value in *ngIf within Angular 2. I conducted an experiment <ion-fab right bottom *ngIf="shouldDisplayFlag()"> Unfortunately, an error is being encountered during this ...

Bootstrap dropdown menu hidden behind other elements

I am implementing Ng-bootstrap in an Angular 5 project to create a dropdown in the navigation header. While I have managed to make it work, the dropdown appears behind the other elements in my container. I would like it to be displayed in front. Here is h ...

Unique validation for mandatory selection on changeSelected

In my Angular HTML code, I have set up a dropdown and two text-boxes. My goal is to create a feature where, if the user selects an option from the 'payable_frequency' dropdown, then either one of the 'payable_commission' fields (min or ...

Warning issued by Angular 7 indicating the usage of the routerLink directive and advising against navigation triggered outside the Angular zone

Encountering difficulties while working with the Angular framework to ensure smooth functioning of my application, I am currently facing an obstacle with routing. The structure includes a main AppComponent and a app-routing.module.ts file for navigation ma ...

Ag-grid with Angular 2 allows users to easily edit entire columns with just a few

I need help modifying a column in my ag-grid. My ag-grid currently looks like this: grid image I want to update all values in the column Etat to be arrêté, but I'm struggling to make it work. This is the code I've been trying: private gridO ...