首页 > 解决方案 > 使用组件通信的 Crud 操作(@Input(),@Output())在角度中,如何在编辑后更新表格行

问题描述

Stackblitz 链接 https://stackblitz.com/edit/angular-bkjfxe?file=src%2Fapp%2FcomponentCommunication

  1. 如何在Id不使用表单在addUser()方法内发布数据的情况下动态添加
  2. 以及如何更新已编辑的项目ngSubmit

我创建了一个servive my-service.service.ts获取、发布和更新服务器数据和来自的数据https://jsonplaceholder.typicode.com/users

我的服务.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class MyServiceService {

  url = 'https://jsonplaceholder.typicode.com/users';
  constructor(private http: HttpClient) {}

  getUsers() {
    return this.http.get(this.url);
  }

  postUsers(user) {
    return this.http.post(this.url, user);
  }

  updateUser(user) {
    return this.http.put(this.url + '/' + user.id, user);
  }

}

我的父组件是master.component.html

主组件.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { MyServiceService } from '../my-service.service';
import { StudentComponent } from '../student/student.component';

@Component({
  selector: 'app-master',
  templateUrl: './master.component.html',
  styleUrls: ['./master.component.scss']
})
export class MasterComponent implements OnInit {
  users: any = [];

  constructor(private _userService: MyServiceService) {}

  @ViewChild(StudentComponent)
  stuComp: StudentComponent;

  ngOnInit() {
    this.getData();
  }

  getData() {
    this
      ._userService
      .getUsers()
      .subscribe((data: any) => {
        this.users = data;
        console.log(this.users);
      });
  }

  removeEmp(n: number) {
    this.users.splice(n, 1);
  }

  addUser(event) {
    this._userService.postUsers(event)
      .subscribe(myData => this.users.push(myData));
  }

  public edittUser(user, i) {
    this.stuComp.userForm.setValue({
      id: i,
      name: user.name,
      username: user.username,
      email: user.email,
      phone: user.phone,
      website: user.website
    });
  }

}

master.component.html我创建了一个表格来显示服务器数据 master.component.html

<div style="background-color: dodgerblue; text-align:center; margin-bottom:20px">
  <h1 align="center" style="margin-top: 0px; padding:20px; color: #fff; display:inline-block">Angular Component Communication</h1>
  <span class="glyphicon glyphicon-plus-sign" style="float:right"></span>
</div>
<div class="container">

  <app-student (onAdd)="addUser($event)" [formData]="user"></app-student>

  <div class="container">
    <table class="table table-striped thead-light table-hover">
      <caption>User Details</caption>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>User Name</th>
          <th>Email</th>
          <th>Address</th>
          <th>Phone</th>
          <th>Website</th>
          <th>company</th>
          <th>Edit</th>
          <th>Delete</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let user of users; index as i">
          <td> {{user.id}} </td>
          <td> {{user.name}} </td>
          <td> {{user.username}} </td>
          <td> {{user.email}} </td>
          <td> {{user.phone}} </td>
          <td> {{user.website}} </td>
          <td><span class="fa fa-edit" style="color:blue" (click)="edittUser(user,i)"></span></td>
          <td><span class="fa fa-trash" style="color:red" (click)="removeEmp(i)"></span></td>
        </tr>
      </tbody>
    </table>
  </div>
  <div>
    <input #elementToCopy (click)="copyInputMessage(elementToCopy)" />
    <button (click)="copyInputMessage(elementToCopy)">Copy</button>
  </div>
</div>

现在看看我使用过的子组件和@Input()student.component.ts (child Component)@Output()Component Communication

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-student',
  templateUrl: './student.component.html',
  styleUrls: ['./student.component.scss']
})
export class StudentComponent implements OnInit {
  obj: any;

  @Input() formData: any = [];
  @Output() onAdd = new EventEmitter();

  userForm = new FormGroup({
    id: new FormControl(''),
    name: new FormControl(''),
    username: new FormControl(''),
    email: new FormControl(''),
    phone: new FormControl(''),
    website: new FormControl('')
  });

  constructor() {}

  onSubmit() {
    this.obj = this.userForm.value;
    this.onAdd.emit(this.obj);
    console.log(this.userForm.value)
    this.userForm.reset();
  }

  ngOnInit() {

  }

}

对于 Crud 操作,我Reactive Formchild component student.component.html中设计了一个

<div class="col-sm-6 col-sm-offset-3" style="background-color: #1e90ffa3; border-radius:4px; padding-bottom:15px;">
  <span class="anchor" id="formLogin"></span>

  <!-- form card login with validation feedback -->
  <div class="card card-outline-primary">
    <div class="card-header ">
      <h3 class="mb-0 card-te">User Form</h3>
    </div>
    <div class="card-body">
      <form class="form" role="form" [formGroup]="userForm" (ngSubmit)="onSubmit()" autocomplete="off" id="loginForm" novalidate="" method="POST">
        <div class="form-group" hidden>
          <label for="uname1">ID</label>
          <input type="text" class="form-control" formControlName="id" name="id" id="uname1">
          <!-- <div class="invalid-feedback">Please enter your id</div> -->
        </div>
        <div class="form-group">
          <label>Name</label>
          <input type="text" class="form-control" formControlName="name" name="name" id="pwd1">
          <!-- <div class="invalid-feedback">Please enter your name</div> -->
        </div>
        <div class="form-group">
          <label>Username</label>
          <input type="text" class="form-control" formControlName="username" name="username" id="pwd2">
          <!-- <div class="invalid-feedback">Please enter your username</div> -->
        </div>
        <div class="form-group">
          <label>Email</label>
          <input type="email" class="form-control" formControlName="email" name="email" id="pwd1" email>
          <!-- <div class="invalid-feedback">Please enter your valid Email</div> -->
        </div>
        <div class="form-group">
          <label>Phone</label>
          <input type="tel" class="form-control" formControlName="phone" name="phone" id="pwd1">
          <!-- <div class="invalid-feedback">Please enter your phone number</div> -->
        </div>
        <div class="form-group">
          <label>Website</label>
          <input type="text" class="form-control" formControlName="website" name="website" id="pwd1">
          <!-- <div class="invalid-feedback">Please enter your website</div> -->
        </div>
        <button type="submit" class="btn btn-success btn-lg" id="btnLogin">Add user</button>
      </form>
    </div>
    <!--/card-body-->
  </div>
  <!-- /form card login -->
</div>

标签: htmlangulartypescriptbootstrap-4components

解决方案


推荐阅读