Angular 2 - One-Stop Form Component for Creating and Modifying

Seeking advice on how to efficiently reuse my Form Component.

Data Model:

class Contact {
  id?: String;
  name: String;
}
  • When a new Contact is created, the id is optional in the model as it doesn't exist at that point.

  • When editing a Contact, the id exists but is not editable and therefore not part of the form.

Behavior:

The Edit and Create views should utilize the same Form @Component since they share the same fields and validation rules.

However, each view must have different actions. For example, the Edit view requires Delete and Reload buttons, and the Save buttons for both views need to perform different actions (Create uses a POST request, Edit uses a PATCH request).

Attempts / Challenges:

I have created a ContactCreateComponent and a ContactEditComponent, both containing

<contactForm [contact]="contact"></contactForm>
in their templates. To handle the different button actions, I placed them within the Create and Edit Components.

The ContactFormComponent includes <form [formGroup]="form"> and

<input formControlName="name">
tags.

I am struggling with extracting the form data from the ContactFormComponent when the Save Button is clicked.

Thoughts / Ideas:

One approach could be defining the FormGroup inside the Create and Edit Components and passing the instance to the Form Component using @Input. This would allow for reading/updating/resetting the Form Data. However, duplicating the FormGroup definition and validators seems redundant, as it should ideally be centralized within the Form Component.

(Avoiding two-way binding on the @Input property due to immutability of Contact)

Any suggestions on how to tackle this issue?

Answer №1

Struggling to extract the form data from the ContactFormComponent when clicking the Save Button.

Add a reference to the form in your component by using

@ViewChild("form") form: ContactForm;
Then you can access the editing contact with form.contact.

Instead of creating separate components, simply determine if the form is for creating or editing. By doing this, you can remain in the same form and dynamically change the action of the Save button from Create Form to Edit Form.

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

How to eliminate arrows in ngx-bootstrap datepicker?

I recently started working with Angular and Bootstrap and I'm facing an issue. I am using a ngx bootstrap datepicker, but I would like to remove the standard arrows on the buttons of the datepicker calendar. Here is a screenshot of the problem: https ...

Is it necessary to unsubscribe from multiple switchmaps?

Consider the following scenario: Should I implement an unsubscribe in each instance of switchMap? And is it necessary to include a takeUntil after every switchMap operation? this.sharedSrv.postDetail.pipe( switchMap(post => { if (post) { th ...

Neither of the elements within the ngIf statement is visible despite the fact that one of them should evaluate to true

I'm currently grappling with using ngIf to conceal a component's details until the necessary variable is set. During this waiting period, it should display a loading message. Despite my efforts to find a solution through online searches, I'v ...

Refreshing the Mat Dialog content when removing items in Angular Material

I have successfully implemented a mat dialog table with 3 columns - name, email, and delete icon. When the user clicks on the delete icon, it prompts a confirmation message to confirm the deletion. Upon confirming, the item is removed from the database. Ho ...

The Radio Button's value appears in a distinct way on Ionic Angular

I am currently working with the Ionic framework and I am trying to display data values on radio buttons. However, I am facing difficulties in retrieving the correct value and setting it appropriately. index.html <td> <label>{{learn ...

Guide on transferring information obtained from a service to an Angular datatable

Recently, I started working on Angular 4 and encountered an issue while trying to display data from an Angular service in JSON format using angular-datatable. Despite trying various options, I am unable to get the data to display within the columns of the ...

Shuffle and Place indented list

I have a bunch of ideas and a list of projects. I need to choose one idea and match it with a project. I followed this guide to implement the drag and drop feature, but encountered an issue where every project gets assigned the same idea when dragging and ...

Behavior of routing not functioning as anticipated

In my app-routing.module.ts file, I have defined the following routes variable: const routes: Routes = [ { path: '', redirectTo: '/users', pathMatch: 'full' }, { path: 'users', component: UsersComponent }, ...

Is there a way to update the Angular component tag after it has been rendered?

Imagine we have a component in Angular with the selector "grid". @Component({ selector: 'grid', template: '<div>This is a grid.</div>', styleUrls: ['./grid.component.scss'] }) Now, when we include this gri ...

Ways to display the initial letter of the surname using Angular

I need help displaying the full first name and first letter of the last name. For example, if the name is John Doe, I want it to show as John D. Currently, my code is not displaying all the letters from the last name. Here is what I have tried: <div cl ...

Concealing the parent view in Angular 2

I need to hide the above parent view. https://i.stack.imgur.com/CZFTn.jpg Here is my code. Upon clicking any of the boxes, the parent should be hidden and the child should appear. <app-navbar></app-navbar> <div class="cont ...

Deploying an Angular application on Firebase is a great way to

I am facing an issue with hosting my Angular(5) project on Firebase. Although I have successfully deployed the application, when I access the project URL, it displays a default Firebase hosting screen instead of my actual Angular project. https://i.stack. ...

Angular Error: Unable to access properties of null (specifically 'validators')

I am encountering an issue with my Angular code where I receive the error message "TypeError: Cannot read properties of null (reading '_rawValidators')". import { Component, OnInit } from '@angular/core'; import { Wifi } from './wi ...

Why is the selected option not visible in the Angular 8 drop-down?

This is a commonly asked question, but my situation seems to be unique. None of the existing answers have provided a solution for my specific issue. Here is the code that I am working with: <form (ngSubmit)="getExceptions(f)" #f="ngForm"> ...

Sorting and paginating the PrimeNG data table causes the webpage to automatically scroll to the top

Currently utilizing PrimeNG Datatable with pagination enabled. When attempting to sort a column or click on pagination buttons, the page automatically scrolls to the top. This behavior is due to the default href="#" in Primeng anchor tags. For example: & ...

A guide to utilizing a signed URL and the Ionic camera plugin in Ionic 4 to upload images to Amazon S3

As I work with the Ionic Native plugin for image uploading using S3 signed URLs, I am encountering an issue due to the camera plugin generating images in base64 format. This is causing difficulties when trying to upload them in the correct format. takePho ...

Tips for associating an id with PrimeNg menu command

Within my table, I have a list of items that I would like to enhance using PrimeNg Menu for dropdown menu options. The goal is to enable navigation to other pages based on the selected item id. When a user clicks on a menu item, I want to bind the id of th ...

Observing changes in the DOM using Angular

Is there a way to programmatically track the changes of a DOM node? It can be time-consuming to detect the delta in the inspector, especially with angular components that have many class names. https://i.stack.imgur.com/ns6rR.png I am looking for a more ...

What steps can be taken to prevent a tab click from causing issues?

Within my application, there is a tab group that contains four tabs: <ion-tabs> <ion-tab [root]="tab1Root" tabTitle="Programmes" tabIcon="icon-programmes"></ion-tab> <ion-tab [root]="tab2Root" (ionSelect)="studioCheck()" tabTitle= ...

Disabling the Parent Component Form Submit button until the child component fields are deemed valid

I'm currently utilizing a Template Driven Form. HTML of the Parent Component <form #BasicForm="ngForm" (ngSubmit)="onBasicDetailsSubmit()" id="BasicForm"> <app-input-text [(sharedVar)]="dashboardDetails.Text1" [isMandatory]="true" >&l ...