2

I am doing a project that need to display an array and user can add in new data or delete existing data from the array.

I am stuck with how to add and delete item from array.

I tried to use push function to add and pop function to delete but failed.

HTML

<div class="write">
    <h1>Student Details</h1>
    <div class="data" *ngIf="selectedStudent">
        <li> Name: <input type="text" [(ngModel)]="name" placeholder="Please enter Name" value={{selectedStudent.name}}>
        </li>
        <li> Age:<input type="text" [(ngModel)]="age" placeholder="Please enter Age" class="age"
                value={{selectedStudent.age}}></li>
        <li>College:<input type="text" [(ngModel)]="college" placeholder="Please enter College"
                value={{selectedStudent.college}}></li>
    </div>

    <p>
        <button class="btnA" onclick="addStudent()">Add</button>
        <button class="btnE" onclick="editStudent()">Edit</button>
        <button class="btnD" onclick="deleteStudent()">Delete</button>
    </p>

    <li *ngFor="let student of student" [class.selected]="student === selectedStudent" (click)="onSelect(student)">
        <span class="badge">{{student.name}} {{student.age}} {{student.college}}</span>
    </li>
</div>

.ts

export class WriteComponent implements OnInit {

    name: string;
    age: number;
    college: string;
    student = STUDENTS;
    selectedStudent: Student;

    constructor() {}
    ngOnInit(): void {}

    onSelect(student: Student): void {
        this.selectedStudent = student;
    }

}

mock-student.ts (where I store my array)

import { Student } from './student';

export const STUDENTS : Student[]=[
  {name:'Johnny',age:24,college:'Harvard'},
  {name:'Samantha',age:20,college:'INTI'},
  {name:'Aditya',age:21,college:'Sunway'},
  {name:'Troy',age:25,college:'TARUC'},
]

This is how the project look like, when I click that list of student the details will be displayed on the form.

3
  • What have you tried so far? What are you having trouble with? Handling events in Angular? Modifying arrays in javascript? Anything else? Commented Feb 20, 2020 at 9:39
  • I tried to use push and pop function to add and delete item in array, I am having trouble to add and delete item in array. Commented Feb 20, 2020 at 9:46
  • 1
    You might want to share the add/delete code block that you have tried so far to actually track the issue. Commented Feb 20, 2020 at 9:49

2 Answers 2

3

Hope this helps.....

Result: enter image description here

app.component.html

<div class="container">
<h2>Add User</h2>  
<form class="form-inline" autocomplete="off" (submit)="addStudent()">
    <div class="form-group">
      <label for="email">Name:</label>
      <input type="text" class="form-control" id="name" name="name" [(ngModel)]="user.name">
    </div>
    <div class="form-group">
      <label for="pwd">Age:</label>
      <input type="number" class="form-control" id="age" name="age" [(ngModel)]="user.age">
    </div>
    <div class="form-group">
        <label for="pwd">College:</label>
        <input type="text" class="form-control" id="college" name="college" [(ngModel)]="user.college">
      </div>
    <button type="submit" class="btn btn-success">Submit</button>
</form>

<div class="user-list" *ngIf="usersList && usersList.length">
    <h2>List of Users</h2>           
    <table class="table table-condensed">
        <thead>
        <tr>
            <th>SL.No</th>
            <th>Name</th>
            <th>Age</th>
            <th>College</th>
            <th>Action</th>
        </tr>
        </thead>
        <tbody>
            <tr *ngFor="let user of usersList; let i = index">
                <th>{{i}}</th>
                <td>{{user.name}}</td>
                <td>{{user.age}}</td>
                <td>{{user.college}}</td>
                <td>
                    <button style="margin-right: 5px;" class="btn btn-warning" (click)="editStudent(i)">Edit</button>
                    <button class="btn btn-danger" (click)="deleteStudent(i)">Delete</button>
                </td>
            </tr>
        </tbody>
    </table>
</div>

app.component.ts

export class AppComponent implements OnInit{
  user: User;
  usersList: User[] = []

  ngOnInit(): void {
   this.resetForm();
  }

  addStudent() {
   this.usersList.push(this.user);
   this.resetForm();
  }

  editStudent(index: number) {
    this.user = this.usersList[index];
    this.deleteStudent(index);
  }

  deleteStudent(index: number) {
    this.usersList.splice(index, 1);
  }

  resetForm() {
   this.user = {age: null, name: '', college: ''};
  }
}

interface User {
 name: string;
 age: string;
 college: string;
}
Sign up to request clarification or add additional context in comments.

6 Comments

Good effert bro +1 for the effort
This is totally helpful!
Can I ask what is the function of *ngIf="usersList && usersList.length"?
And why if I add the onSelect(username) and {{selectedUser.name}} then the array list will dissapear?
*ngIf="usersList && usersList.length" by adding this even id the array is not defined code doesn't break
|
0

Deleting an item from the array

You are setting your selectedStudent to one of the instances in your array, so it is simple enough to find its index when you want to remove it from the array.

You can use the splice array function to remove the item at the index.

// declare students here for the purpose of the answer
students: Student[] = [
  {name:'Johnny', age:24, college:'Harvard'}
  // ... more students here
];
selectedStudent : Student;

onSelect(student:Student): void {
  this.selectedStudent = student;
}

deleteStudent(): void {
  if (!this.selectedStudent) {
    return;
  }

  // find the index of the selected student
  // this works because your selected student is one of the array items
  // it wouldn't work if selected student was a copy
  const index = this.students.indexOf(this.selectedStudent);

  // use splice to remove 1 item starting at the given index
  this.students.splice(index, 1);

  // todo: logic to reset this.selectedStudent
}

Adding an item to the array

Adding is simple. Use the push array function to append an item to an array.

students: Student[] = [];

name: string;
age: number;
college: string;

addStudent() {
  const student = { 
    name: this.name,
    age: this.age,
    college: this.college
  };

  this.students.push(student);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.