Steps for customizing ngxdatatable with modal dialog in Angular 2


  • My Objective

    I have a collection of office names and departments in my ngxdatatable. Each office name is accompanied by an edit and delete button, allowing users to modify or remove the respective office name/department.

    Specifically for editing purposes, I am looking to implement a modal dialog that appears when the edit button is clicked (linked to an edit function). This dialog should display the details of the office name and department, enabling users to make edits to them and save the changes.

  • Current Progress

    I have successfully implemented the pop-up modal when users click the edit button. However, I am facing difficulties passing the original values to the edit modal dialog.

  • The Issue at Hand

    My main challenge lies in transferring the original values to the modal dialog (currently resolving this) and providing users with the ability to edit both the office name and department before saving the updated information.

Code Snippet: Modal Dialog Implementation

<div bsModal #editOffice="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-md">
        <div class="modal-content">
            <form [formGroup]="EditOfficeForm" (ngSubmit)="EditOfficeForm.valid && updateOffice(EditOfficeForm.value)" novalidate>

                <div class="modal-header">
                    <button type="button" class="close" (click)="editOffice.hide()" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">Edit Office</h4>
                </div>

                <div class="modal-body">
                    <div class="form-group row">
                        <label class="col-md-3 form-control-label" for="text"> Office Name</label>
                        <div class="col-md-4">
                            <input #officeName type="text" id="officeName" name="officeName" class="form-control" formControlName="officeName" value="{{editingData.officeName}}">
                            <div class='redColor' *ngIf="EditOfficeForm.controls.officeName.touched">
                                <div *ngIf="EditOfficeForm.controls.officeName.hasError('required')">
                                    Required.
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-group row">
                        <label class="col-md-3 form-control-label" for="text"> Department </label>
                        <div class="col-md-4">
                            <input #dept type="text" id="dept" name="dept" class="form-control  ng-pristine ng-valid ng-touched"
                                formControlName="dept" value="{{editingData?.dept}}">
                            <div class='redColor' *ngIf="EditHolidayForm.controls.dept.touched">
                                <div *ngIf="EditHolidayForm.controls.dept.hasError('required')">
                                    Required
                                </div>
                            </div>
                        </div>
                    </div>   

                    <button type="button" class="btn btn-space pull-right" (click)="editOffice.hide()" aria-label="Close"> Cancel </button>&nbsp;
                    <button class='btn btn-primary' type='submit' (click)="editOffice.hide()" [disabled]='!EditOfficeForm.valid'>Submit</button>

                    <br>

                </div>

            </form>
        </div>
    </div>
</div>

Component File Section

export class OfficeComponent {

    @Output() public rowEdited: EventEmitter<any> = new EventEmitter();
    public editingData:EditingRowData;

    EditOfficeForm: FormGroup;
    officename: FormControl;
    dept:FormControl;

    constructor(private fb: FormBuilder, public http: Http, private dataService: DataService) {

        this.EditOfficeForm= fb.group({
            officename: this.officename,
            dept:this.dept
        })

    }

    ngOnInit() {
        this.getAllOffice();
    }

    getAllOffice()
    {
        /// fetching all offices from service
    }

    editOffices(rowDetails:any): void
    {
        this.rowEdited.emit({rowDetails});
        console.log('row details', { rowDetails });

        //PASSING THIS VALUE TO THE POP-UP DIALOG  

        this.editingData = rowDetails
        // this.editingData CONTAINS ALL THE SELECTED OFFICE NAME AND DEPARTMENT DETAILS. 
        // HENCE, I WISH TO DISPLAY THIS DATA IN MY MODAL DIALOG HTML.

    }

    updateOffice(value: Object): void {
        //updating and sending to database
    } 
}

I keep encountering the issue where officename is undefined, and I attempted using editingData?officename which began displaying in my modal dialog. However, if the user only alters the office name, leaving the department as it was originally, the captured value becomes

{officename:"newOfficename", dept:null}
.

Hence, I aspire for the details to be edited accurately and saved correctly.

If the user modifies only one element (office name or department), solely that particular item should be changed, while preserving the rest of the data untouched.

Answer №1

During the editing process, after selecting a row to edit, you will likely need to update the EditOfficeForm formGroup with the relevant editingData. An example of how this can be achieved is as follows:

this.EditOfficeForm.patchValue(this.editingData);

Answer №2

If you want to display a Modal, try adding a basic button in your HTML code:

<button type="button" class="btn btn-primary"  data-target="#editModal" (click)="updateOffice(row)" data-toggle="modal" data-original-title="Edit">
        Edit
</button>

Make sure to assign an id to your modal and use the same id as the data-target in your button element. To populate the edit fields in the form, implement your updateOffice() method like this:

updateOffice(row: object){
  this.EditOfficeForm.setValue({
  officename: row.officename,
  dept: row.dept
});
}

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

Enhancing the aesthetic appeal of Angular2 Google Maps

Hey there, I'm a newcomer to Angular2/Typescript and I've been working on styling a map in my Angular2 project. I integrated a map using the Angular2 Google Maps Components, but I'm having trouble with applying styles through the undocumente ...

Guide on retrieving an ArrayList() from intricate function in Angular

Simplicity is the key to my question. Let's take a look at this Angular method: getAllOrdersHeaders(){ this.getAllOrdersIds().subscribe(idList=>{ idList.forEach(id=>{ this.ordersCollection.doc(id).collection('metadata&apo ...

The data type 'AbstractControl | null' cannot be assigned to type 'FormGroup'

I am facing an issue with passing the [formGroup] to child components in Angular. The error message says Type 'AbstractControl | null' is not assignable to type 'FormGroup'. I have double-checked my conditions and initialization, but I ...

Unable to locate the type definition file for 'jquery'

After updating my NuGet packages, I encountered an issue where I can no longer compile due to an error related to the bootstrap definition file not being able to find the jquery definition file within my project. Prior to the update, the directory structu ...

What is the best way to repeatedly subscribe to an observable?

Within the ngOnInit() function of my Angular application, I am subscribing to an Observable in the following manner: ngOnInit() { this.loadArtistTable(); } loadArtistTable(): void { this._artistService.getArtists().subscribe( (artistL ...

The specified type 'ReturnType' mandates one type argument. Error code: ts(2314)

After transitioning from Flow to Typescript, I have encountered errors while converting some of the codebase. Most of the issues have been resolved using the Utility-Types package, but I am stuck with the code below without any helpful documentation or ans ...

`Inconsistencies in console.log output with Angular Firestore``

I'm currently working on retrieving the id of selected data, but when I test it using console.log, it keeps outputting twice. The image below illustrates the console.log output. https://i.stack.imgur.com/IARng.png My goal is to fetch the id once and ...

Exploring techniques to iterate through this specific JSON data within an Angular frontend

I am looking for assistance in looping the data below into a 'Select dropdown' using Angular 10. The data consists of all the States in India along with their districts. I have retrieved this information from the internet, but I am unsure how to ...

Converting the source to your image assets in Angular: A step-by-step guide

I am looking to update the source code. Here is an example: <div *ngFor="let item of meal.allergenList" class="btn btn-primary"> <img [src]="item" alt=""> </div> I want to make the following co ...

Types with conditions but no common parameter

I am looking to define my props as either type A or B. For instance export default function App() { type Checkbox = { type: "checkbox"; checked: boolean; }; type Dropdown = { type: "dropdown"; options: Array<an ...

In Typescript, an index signature parameter can only be of type 'string' or 'number'

I'm facing an issue with a generic type that defaults to string: interface EntityState<typeOfID = string> { entities: { [ id: typeOfID]: any }; } The error I receive is: An index signature parameter type must be either 'string' or ...

Seeking a solution to the useRef problem. Encountering difficulties with React Hook useRef functionality within a NextJS application

Whenever I refresh the page, the 'Ref' value is displayed as null. This causes the if condition blocks not to work. I attempted to modify the useRef values but could only set it to null. When I console log the myDivRef.current, it returns "Ref: ...

Is there a way to set up a background process within electron that captures a screenshot of the entire desktop?

I'm currently working on a Desktop application using Angular2 and Electron that captures screenshots of the entire desktop and saves them to a specified path on my PC. The code for capturing screenshots is implemented in the app.component.ts file, but ...

Tips for modifying the main text color in Angular Material

Currently, I am utilizing Angular Material v13.0.1 and my goal is to modify the color of the text within my button. <button mat-raised-button color="primary" (click)='submit()' [disabled]='btnDisabled' >Save</ ...

How can I ensure the types of an object while keeping the key as a constant in TypeScript?

I'm currently working on a project where I have an object that needs to meet specific typing requirements. Here is the initial code snippet: export const dateFormat = { hourOnly: { hour: 'numeric' } … } To ensure that the values in t ...

Tips for dynamically passing input data in an Angular Library

I need to receive user input and then send it to an API endpoint located in the services section, however the services section must be transformed into a library. How can I accomplish this data transfer without constantly updating the library or insertin ...

Retrieving data from an Angular 5 Input text field

I have been struggling with what seems like a simple question, but none of the solutions I found seem to work for me. In my component.html file, I have a standard input field: <div class="form-group"> <label>Serial</label> <in ...

The initial pop-up window has a head start on the second one, which is lagging behind

I have a ng prime modal where I am displaying my data. When I try to delete one of the entries by clicking on a button, it is supposed to show a second popup. However, in my case, the second popup appears behind the first one as shown in the examples below ...

VS Code fails to provide auto-suggestions for typed attributes in my library

While working on my React application with a component library, I realized that VS Code isn't providing hints for attributes that are typed with my custom types. Below is a simplified version of the code I'm using: import { ProviderApp } from &ap ...

Creating a Chrome extension with Angular 5: A comprehensive guide

Currently, I am in the process of developing a Chrome extension using Angular 5. Initially, I successfully created a basic Angular app with the help of Angular Material and it functioned perfectly as an Angular application (I used ng build for verification ...