0

i need help in my editing function. I need to load the items to the form when i click the edit button. This is how my app works, first, there is a list of users, then you can click the "view more" button of that specific user and it will redirect you to a new page. In that new page, you will find the "edit button" So I'm trying to do my edit function by selecting it with the contact number since I don't have an index since it's an object. THERE IS ONLY ONE PROBLEM AND THAT IS HOW CAN I LOAD UP ITEMS IN EDITING FORM?. I believe this is a very simple problem but I'm confused about this. If you have any better solution, please help me.

user-detail.component.ts

 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(index: number) {
    this.router.navigate(['users', this.id, 'edit']);
  }

}

user-edit.component.html

<div class="card-block">
      <form (ngSubmit)="onUpdateUser(f)" #f="ngForm">
        <div class="form-group">
          <label for="First Name">First Name</label>
          <input type="text" class="form-control" [(ngModel)]="user.f_name" name="f_name" ngModel required>
        </div>
        <div class="form-group">
          <label for="Last Name">Last Name</label>
          <input type="text" class="form-control" [(ngModel)]="user.l_name" name="l_name" ngModel required>
        </div>
        <div class="form-group">
          <label for="Contact Number">Contact Number</label>
          <input type="number" class="form-control" [(ngModel)]="user.contact_no" name="contact_no" ngModel required pattern="^[1-9]+[0-9]*$">
        </div>    
         <button class="btn btn-warning pull-right" [disabled]="!f.valid"><i class="fa fa-download" aria-hidden="true"></i> Update</button>
      </form>       
    </div>

user-edit.component.ts

  export class UserEditComponent implements OnInit {
  @ViewChild('f') editForm: NgForm;
  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);
    });
  }


  onUpdateUser(form: NgForm) {
       const value = form.value;
       const updatedUser = new User(value.f_name, value.l_name, value.contact_no);
       alert("Successfully Updated");
       this.router.navigate(['users', this.id]);
      }
}

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());
  }

}
Joseph
  • 7,042
  • 23
  • 83
  • 181

2 Answers2

1

You can use two-way binding to load the data and reflect any changes to the data from the UI right away. In your case, for example, you can do it like this:

First, import FormsModule into your module:

import { FormsModule } from '@angular/forms'; // <--- JavaScript import from Angular

@NgModule({
  imports: [
    ....
    FormsModule  // <--- import into the NgModule
    ....
  ],

Then use it like this:

<input type="text" [(ngModel)]="f_name" class="form-control" name="f_name">

Assuming that you have a variable f_name in your component that will load the initial value of the f_name and will contain its updated value.

And please note the exact [()] notation which enables the two-way binding.

Refer to this KB for more details.

Mohsen Kamrani
  • 7,177
  • 5
  • 42
  • 66
  • I think that's not a proper way since I'm coming from the user-detail and loading it to the user-edit form – Joseph Aug 31 '17 at 00:22
  • If you are using template-driven forms (not reactive forms), then yes, using ngModel binding as shown here is the proper way to get data from the component to the template. – DeborahK Aug 31 '17 at 00:40
0

If you use the ngModel binding as mentioned by @mok, then your edit code can be just like your detail code:

  user: User;

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

The user properties will then automatically appear on the form using Angular's two-way data binding. this.user is also automatically updated with the user's entered values.

See the Angular documentation for more information: https://angular.io/guide/forms

DeborahK
  • 57,520
  • 12
  • 104
  • 129
  • That's not how stack overflow works. :-) Feel free to edit your question to clarify what your code looks like now. Or post a new question if you are stuck on another topic. – DeborahK Aug 31 '17 at 04:23
  • I could also suggest a course for you: https://app.pluralsight.com/library/courses/angular-2-forms/table-of-contents You can sign up for a free week. – DeborahK Aug 31 '17 at 04:30
  • Hi Deborah, I already edited the edit function and now works fine. The problem is that I want to use the service to update the users and its information just like what i did to the add and delete function. How can I improve this? Thanks – Joseph Aug 31 '17 at 15:46
  • If you can provide a working plunker of what you have so far, we can take a look. – DeborahK Aug 31 '17 at 21:54
  • Sorry I don't know how to use plunker. And I mean the editing function is already done. I just wonder why it works without service. I just want to use service to make things the same like what i did to add and delete. – Joseph Sep 01 '17 at 03:23
  • Here are the steps for using Plunker: (1) Navigate to this site: https://plnkr.co/edit/?p=catalogue (2) Drop down the list in the big green button and select 'Angular'. (3) Copy your code into the project either within the provided app.ts file or in new files using the New File option in the left column. Hope this helps! – DeborahK Sep 01 '17 at 05:37
  • Is it ok with you if it's in github? – Joseph Sep 01 '17 at 23:02