简体   繁体   English

如何在Angular的数组中添加和删除项目

[英]How to add and delete item from array in Angular

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.我尝试使用push功能添加和pop功能删除但失败了。

HTML 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 .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) mock-student.ts (我存储数组的地方)

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'},
]

这就是项目的样子,当我单击该学生列表时,详细信息将显示在表单上。

Hope this helps.....希望这可以帮助.....

Result:结果: 在此处输入图片说明

app.component.html应用程序组件.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 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;
}

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.您将selectedStudent设置为数组中的实例之一,因此当您想从数组中删除它时,很容易找到它的索引。

You can use the splice array function to remove the item at the index.您可以使用splice数组函数删除索引处的项目。

// 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.使用push 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM