Angular2: Form reset triggers row deletion

In my system, there is a table displaying student data with CRUD functions. Each row in the table has an Edit button.

<table class="table table-bordered table-striped">
        <thead class="studentHeader">
            <tr>
                <td>Roll Number</td>
                <td>First Name</td>
                <td>Last Name</td>
                <td>Gender</td>
                <td></td>
                <td></td>
            </tr>
        </thead>
        <tbody>

        <tr *ngFor="let student of studentList;let i=index">
            <td>{{student.rollNumber}}</td>
            <td>{{student.firstName}}</td>
            <td>{{student.lastName}}</td>
            <td>{{student.gender}}</td>
            <td><button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal" (click)="editStudent(student)">Edit</button></td>
            <td><button type="button" class="btn btn-danger">Delete</button></td>
        </tr>

        </tbody>
    </table>

Below is the modal used for editing:

<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">

        <form #studentForm="ngForm" novalidate>
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Add Student</h4>
                </div>
                <div class="modal-body">
                    <label path="rollnumber"  class="sr-only">Roll Number</label>
                    <input type="text" id="rollNum" class="form-control" [(ngModel)]="studentObj.rollNumber" name="rollnumber" placeholder="Student Roll Number" required autofocus /><br>
                    <label path="firstName"  class="sr-only">First Name</label>
                    <input type="text" id="firstname" class="form-control" [(ngModel)]="studentObj.firstName" name="firstname" placeholder="Student First Name" required /><br>
                    <label path="lastName"  class="sr-only">Last Name</label>
                    <input type="text" id="lastname" class="form-control" [(ngModel)]="studentObj.lastName" name="lastname" placeholder="Student Last Name" required />
                    
                    <h5><span class="label label-default">Gender</span>&nbsp;&nbsp;
                        <input type="radio" name="gender" id="male" value="Male" [(ngModel)]="studentObj.gender">
                        <label for="male">Male</label>&nbsp;&nbsp;
                        <input type="radio" name="gender" id="female" value="Female" [(ngModel)]="studentObj.gender">
                        <label for="female">Female</label><br>
                    </h5>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal" (click)="addStudent(studentObj)" *ngIf="studentAdd">Add</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal" *ngIf="studentUpdate" (click)="updateStudent(studentObj)">Update</button>
                </div>
            </div>
        </form>
        
    </div>
</div>

Lastly, here is the component code:

@ViewChild('studentForm') studentForm: NgForm;
private studentList: Array<StudentDto> = [];
private studentObj: StudentDto = {};
private departmentList: Array<string> = ["Computer Science", "Information Science", "Electronics", "Mechanical", "Civil"];
private studentAdd: boolean = true;
private studentUpdate: boolean = false;

constructor() { }

ngOnInit() {
    this.studentList = StudentData;
}

private addStudent(addStudentObj: StudentDto): void {
    this.studentList.push(addStudentObj);
    this.studentForm.reset();
}

private editStudent(editStudentObj: StudentDto): void {
    this.studentAdd = false;
    this.studentUpdate = true;
    this.studentObj = Object.assign({}, editStudentObj);
}

private updateStudent(updateStudentObj: StudentDto): void {
    for(let i:number = 0; i<this.studentList.length; i++){
        if(this.studentList[i].rollNumber == updateStudentObj.rollNumber){
            this.studentList[i] = updateStudentObj;
        }
    }
    this.studentForm.reset();

}

I am facing an issue where resetting the modal after adding/updating a student leads to the deletion of the corresponding row from the table. How can I reset the modal without affecting the table rows?

Answer №1

Encountered a similar issue with a form and table, which was caused by the two-way binding being used. Resolved it by switching to one-way binding. The solution involved changing [(ngModel)] to [ngModel]. Simply remove the parentheses.

<input type="text" id="lastname" class="form-control" [ngModel]="studentObj.lastName" name="lastname" placeholder="Student Last Name" required />

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

Guide on creating a universal template from a collection of interfaces

Two interfaces, AllTypes type: interface A { // ... } interface B { // ... } type AllTypes = A | B; How can I utilize generics to ensure that a function's argument is an object with either interface A or B? // pseudocode function test<T ...

TypeScript encountered an unexpected { token, causing a SyntaxError

Despite multiple attempts, I can't seem to successfully run my program using the command "node main.js" as it keeps showing the error message "SyntaxError: Unexpected token {" D:\Visual Studio Code Projects\ts-hello>node main.js D:&bsol ...

Error: Trying to access property '2' of a null value

I’ve been working on a project using Next.js with TypeScript, focusing on encryption and decryption. Specifically, I’m utilizing the 'crypto' module of Node.js (@types/nodejs). However, I encountered an error while attempting to employ the &a ...

Encountering the error message "Receiving 'Multiple CORS header 'Access-Control-Allow-Origin' not allowed' while accessing my Laravel API from Angular"

After successfully developing an API with Laravel that functioned perfectly with Postman, I am now working on its front-end using Angular. However, I keep encountering this error every time I send a request to the API: Cross-Origin Request Blocked: The Sa ...

What strategies can I implement to reduce the size of my Angular application to 500K or less?

I have been researching ways to reduce the size of my Angular application, but have not yet found a solution that significantly decreases its size. Currently, my application is 4M in production and 14M in development. So far, I have tried: Lazily loadin ...

When choosing the child option, it starts acting abnormally if the parent option is already selected in Angular

I am encountering an issue while trying to select the parent and its children in the select option. The concept is to have one select option for the parent and another for the child. I have parent objects and nested objects as children, which are subCatego ...

There are currently no members available for export

Inside the file app/graph-options/options.ts, I am exporting a variable: export let lineChartLevel2: string = "EXPORT"; Now, in app/level-2/level-2.component.ts, I am trying to import this variable: import { lineChartLevel2 } from '../graph-options ...

Is there an issue with my approach to using TypeScript generics in classes?

class Some<AttributeType = { bar: string }> { foo(attrs: AttributeType) { if (attrs.bar) { console.log(attrs.bar) } } } Unable to run TypeScript code due to a specific error message: Property 'bar' d ...

I am encountering a TypeScript error when using the createRef() method in React JS

Encountering some TypeScript warnings with the following dependencies: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8df9f4fde8feeeffe4fdf9cdbea3b8a3bf">[email protected]</a>, <a href="/cdn-cgi/l/email-protect ...

Angular: Module's library folder missing from node_modules directory

I am facing an issue with my Angular module (Framework) that relies on another Angular module (pv-config). The pv-config module is integrated as a git-submodule in the Framework module. During installation / building process, the following steps occur: F ...

Incorporate a dropdown menu into the account configuration page

I'm currently enhancing my abp project with the latest version using Angular. My goal is to integrate a combo box into the account section located under the Personal Settings tab. https://i.sstatic.net/e0WmC.png While researching, I came across the ...

What is the best way to transform an array of objects into a nested array through shuffling

I am dealing with a diverse array of objects, each structured in a specific way: data = [ { content: { ..., depth: 1 }, subContent: [] }, { content: { ..., depth: 2 ...

How can we include additional types for external npm packages in a React TypeScript project?

Recently, I encountered an issue while using the react-microsoft-login package from npm. I included a button in the children property and received a typescript error stating that "property 'children' does not exist on type 'intrinsicattribut ...

When running `npm test`, Mocha TS tests encounter failure, but the issue does not arise when executing them

When running tests in my Typescript nodejs project, I use the following command: mocha --compilers ts:ts-node/register,tsx:ts-node/register The tests run successfully with this command. However, when I try to run them using npm test, I encounter the foll ...

There was a mistake: _v.context.$implicit.toggle cannot be used as a function

Exploring a basic recursive Treeview feature in angular4 with the code provided below. However, encountering an error when trying to expand the child view using toggle(). Encountering this exception error: ERROR TypeError: _v.context.$implicit.toggle i ...

Tips for properly executing directives in sequential order while using async in Angular 13

I created a standard registration form using Angular and implemented an async directive (UserExistsDirective) to validate if the email is already taken. To manage error messages, I also utilized a second directive (ValidityStyleDirective) which is also use ...

Exploring the capabilities of supertest by testing endpoints in Express with NodeJS

Having trouble setting up a test environment to test my TypeScript Express Node.js endpoints. Here are the packages I've installed: jest ts-jest jest-junit supertest @types/supertest @types/jest This is how my spec file looks like: imp ...

Examined unexplored branch that is a component of the OR condition

I am looking to test an uncovered branch in my codebase. Here is the scenario: https://i.sstatic.net/ZBKgi.png The test involves: describe('addCourseContentCard()', () => { it('should add course content card', () => { ...

Exploring the power of combining React, styled-components, and TypeScript: Creating a functional component that encapsulates a styled component

Struggling to create a wrapper for my styled component with proper types. Imagine having a styled component defined like this: const Button = styled.button<ButtonProps>` background-color: ${(props) => props.color}; `; Now the goal is to have a ...

Transforming an Observable to a boolean using RXJS

Hey there, I'm currently working on creating a function similar to this: verify(){ return this.http.post(environment.api+'recaptcha/verify',{ token : this.token }).pipe(map(res=>res.json())); } I want to be able to use ...