Edit Item in Angular 4

2.6k views Asked by At

Can anyone help me in my editing function. I am confused on how to make this work. I've done my best on my codes below but i can't get it. I already loaded the items in the input but i can't update a new one. I mean i don't know how to override the items that is selected

user-detail.component.ts

import { Component, OnInit } from '@angular/core';
import { User } from '../user.model';
import { UserService } from '../user.service';
import { ActivatedRoute, Params, Router } from '@angular/router';

@Component({
  selector: 'app-user-detail',
  templateUrl: './user-detail.component.html',
  styleUrls: ['./user-detail.component.css']
})
export class UserDetailComponent implements OnInit {

    user: User;
    id: number;

  constructor(private userService: UserService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
      this.route.params
      .subscribe(
        (params: Params) => {
          this.id = +params['id'];
          this.user = this.userService.getUser(this.id);
          }
        )
  }

  onEditDetail(){
    this.router.navigate(['/user/user-list/edit', this.id]);
  }


}

user.edit.component.ts

import { Component, OnInit, ViewChild} from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { User } from '../user.model';
import { UserService } from '../user.service';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-user-edit',
  templateUrl: './user-edit.component.html',
  styleUrls: ['./user-edit.component.css']
})
export class UserEditComponent implements OnInit {
  @ViewChild('f') editForm: NgForm;
  user: User;
  id: number;
  editedItem: User;

  constructor(private userService: UserService, 
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
      this.route.params
      .subscribe(
        (params: Params) => {
          this.id = +params['id'];
          this.user = this.userService.getUser(this.id);
        }
      )  
  }

  onUpdateDetails(){
      this.editForm.setValue({
          f_name: this.editedItem.f_name,
          l_name: this.editedItem.l_name,
          contact_no: this.editedItem.contact_no
      })
  }



}

user.edit.component.html

 <div class="container">
  <div class = "row">
    <div class="col-md-4"></div>
    <div class = "col-md-5">
      <div class="card text-center">
        <div class="card-header">
          <h4>EDIT USER</h4>
        </div>
        <div class="card-block">
          <form>

            <div class="form-group">
              <label for="First Name">First Name</label>
              <input type="text" class="form-control" value="{{user.f_name}}">
            </div>
            <div class="form-group">
              <label for="Last Name">Last Name</label>
              <input type="text" class="form-control" value="{{user.l_name}}">
            </div>
            <div class="form-group">
              <label for="Contact Number">Contact Number</label>
              <input type="number" class="form-control" value="{{user.contact_no}}">
            </div> 

            <a href="#" class="btn btn-block"><i class="fa fa-pencil-square-o" aria-hidden="true" (click)="onUpdateDetails"></i> UPDATE</a>
          </form>       
        </div>
      </div>
    </div>
  </div>
</div>

user.service.ts

import { User } from './user.model';
import { Subject } from 'rxjs/Subject';
export class UserService {

usersChanged = new Subject<User[]>();

  private users: User[]= [
    new User('Harry', 'James', 99999889),
    new User('Thomas', 'Baker', 99638798)
  ];

  getUsers() {
    return this.users.slice();
  }

  getUser(index: number) {
    return this.users[index];
  }

  addUser(user: User){
    this.users.push(user);
    this.usersChanged.next(this.users.slice());
  }

  deleteUser(index: number){
    this.users.splice(index, 1);
    this.usersChanged.next(this.users.slice());
  }


}
1

There are 1 answers

3
Rajez On

you can use Reactive Forms to handeling forms:

import { FormGroup, FormBuilder } from '@angular/forms';

export class UserEditComponent implements OnInit {
  editForm: FormGroup;

  constructor(formBuilder: FormBuilder, ...) {
      // Building Form
      this.editForm = formBuilder.group({
          'f_name': [''],
          ... 
      })

  }

    onUpdateDetails(){

      // Updating form value
      this.editForm.patchValue({
          'f_name': this.editedItem.f_name,
          ...
      });
      this.editForm.updateValueAndValidity();
    }

.

 // Using reactive form in template
<form [formGroup]="editForm">
   <div class="form-group">
      <label for="First Name">First Name</label>
      <input type="text" formControlName="f_name" class="form-control" />
   </div>
 ...