Stackblitz Link
https://stackblitz.com/edit/angular-bkjfxe?file=src%2Fapp%2FcomponentCommunication
- как добавить
Id
динамически, не используя форму для размещения данных внутри addUser()
метод
- И как обновить отредактированный элемент на
ngSubmit
Я создал servive
my-service.service.ts
для получения, публикации и обновления данных сервера и передачи данных с https://jsonplaceholder.typicode.com/users
мой-service.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
master.component.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()
и @Output()
для Component Communication
student.component.ts (дочерний компонент)
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 Form
в child 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>