Jijo Robin
Jijo Robin

Reputation: 385

how to edit operation in angular?

I'm trying to build a crud operation. I was able to do create and delete operation. I want the existing data to be shown in the input forms while clicking the edit function and then able to change them. Can someone help me with the edit operation?

Here is my code

service.ts

import { Injectable} from '@angular/core';
import{UserCreation} from '../../models/user-creation.model';
import{Observable} from 'rxjs/Observable';
import{of} from 'rxjs/observable/of';
import{catchError,map,tap} from 'rxjs/operators';
import{HttpClient,HttpHeaders} from '@angular/common/http';

const httpOptions={
headers:new HttpHeaders({'Content-Type':'application/json'})
};

@Injectable({
providedIn: 'root'
})

export class UserCreationService{

constructor(private http:HttpClient) { }

private usersUrl='https://jsonplaceholder.typicode.com/posts';

getUsers():Observable<UserCreation[]>{
return this.http.get<UserCreation[]>(this.usersUrl).pipe(
tap(receivedUsers 
=>console.log(`receivedUsers=${JSON.stringify(receivedUsers)}`)),
  catchError(error=>of([]))
);
}

getUserFromId(id:number):Observable<UserCreation>{

const url=`${this.usersUrl}/${id}`;
return this.http.get<UserCreation>(url).pipe(
  tap(selectedMovie=>console.log(`selected movie 
 =${JSON.stringify(selectedMovie)}`)),
  catchError(error=>of(new UserCreation()))
)
}

updatedUser(user:UserCreation):Observable<any>{

return 
this.http.put(`${this.usersUrl}/${user.id}`,user,httpOptions).pipe(
  tap(updatedUser=>console.log(`updated user 
=${JSON.stringify(updatedUser)}`)),
  catchError(error=>of(new UserCreation()))
)
}

addUser(newUser:UserCreation):Observable<UserCreation>{
return this.http.post<UserCreation> 
(this.usersUrl,newUser,httpOptions).pipe(
  tap((user:UserCreation)=>console.log(`inserted 
movie=${JSON.stringify(user)}`)),
  catchError(error=>of(new UserCreation()))
)
}

deleteUser(userId:number):Observable<UserCreation>{
const url=`${this.usersUrl}/${userId}`;
return this.http.delete<UserCreation>(url,httpOptions).pipe(
  tap(_=>console.log(`Deleted movie with id = ${userId}`)),
  catchError(error=>of(null))
)
}


}

component.ts

I need an edit function here

import { Component, OnInit } from '@angular/core';
import { UserCreation} from '../../models/user-creation.model';
import { UserCreationService } from '../../common/services/user- 
creation.service';

@Component({
selector: 'app-user-management',
templateUrl: './user-management.component.html',
styleUrls: ['./user-management.component.css']
})

export class UserManagementComponent implements OnInit {

allUsers: UserCreation[];

constructor(private userService: UserCreationService) { }


getUsersFromServices():void{
this.userService.getUsers().subscribe(
  (Users)=>{
    this.allUsers=Users;
    console.log(Users);

  }
 )
}

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


add(title:string,body:string):void{
const newUser:UserCreation=new UserCreation();
newUser.title=title;
newUser.body=body;
this.userService.addUser(newUser)
.subscribe(insertedUser=>{
  this.allUsers.push(insertedUser);
});
}


delete(userId:number):void{
this.userService.deleteUser(userId).subscribe(_=>{
  this.allUsers=this.allUsers.filter(eachUser=>eachUser.id!==userId);
})
}

component.html

I want to know what will come in the edit button

<table class="row-border hover">
 <tr *ngFor="let user of allUsers " >
   <td>{{user.title}}</td> <td>{{user.body}}</td>

   <td><button type="button" 
   (click)="Edit()">Edit</button> </td> 

  <td><button type="button" (click)="delete(user.id)">Delete</button> 
  </td>
 </tr>
</table>

<form>
<div class="form-group">
  <label for="text">Title:</label>
  <input type="text" class="form-control" id="text" name="title" 
  #title>
</div>

<div class="form-group">
  <label for="text">Body:</label>
  <input type="text" class="form-control" id="text" name="body" #body                 
</div>

<button type="submit" class="btn btn-primary" 
(click)="add(title.value,body.value); title.value=''; 
body.value=''">Submit</button>
</form>

model.ts

export class UserCreation{
id:number;
title:string;
body:string;
}

Upvotes: 1

Views: 7169

Answers (1)

ksrider 148
ksrider 148

Reputation: 55

In component.html you need to add Id in edit click to find which user detail need to edit also make the Title and Body as two-way data binding model to view the user detail on edit.

<input type="text" class="form-control"  [(ngModel)]="title" id="text" name="title" #title>
<input type="text" class="form-control"  [(ngModel)]="body" id="text" name="body" #body  >

 <button type="button" (click)="Edit(user.id)">Edit</button> 

In component.ts add method Edit(id) to get the detail of user from the user list:

Edit(editUserID){
var user = this.allUsers.find(user=>user.id == editUserID);
this.title=user.title;
this.body=user.body;
}

In save button click you can update the user list using the ID.

Upvotes: 1

Related Questions