Pass ID(Index) to onEditDetail() Parameters

76 views Asked by At

How can i pass the value index or id to EditDetail() parameters. I want it to be put inside the parenthesis of onEditDetail() once i click the onEditDetail() in html

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

onEditDetail(id: string) {
  console.log(id);
}

user-detail.component.html

 <div class="container">
  <div class = "row">
    <div class="col-md-3"></div>
    <div class = "col-md-8">
      <div class="card">
        <div class="card-header">
          {{ user.l_name}} 's Complete Information<span class="pull-right"><input class="form-control" placeholder="Search User" name="srch-term" id="srch-term" type="text"></span>
        </div> 
        <table class="table table-responsive">
          <thead class="thead-default">
            <tr>
              <th>First Name</th>
              <th>Last Name</th>
              <th>Contact Number</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>{{ user.f_name }}</td>
              <td>{{ user.l_name }}</td>
              <td>{{ user.contact_no }}</td>
              <td><button class=" btn btn-primary" style="cursor: pointer;" (click)="onEditDetail()">Edit</button> </td>
            </tr>
          </tbody>
        </table>     
      </div>
    </div>
  </div>
</div>
3

There are 3 answers

1
L.Wonbae On

You can do that

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

      // Your method call
      this.onEditDetail(this.id);
    });
}

onEditDetail(id: string) {
  console.log(id);
}
0
Kunvar Singh On
ngOnInit() {
  this.route.params
    .subscribe((params: Params) => {
      this.id = +params['id'];
      this.onEditDetail(this.id); //call onEditDetails and pass id to it.
      this.user = this.userService.getUser(this.id);
    });
}

onEditDetail(id: any) {
  console.log(id);
}
14
Dheeraj Kumar On

Adding to other answers,

You need to understand that you are making an asynchronous call.

So If you need to access id anywhere else, you need to get that on completion of asynchronous call, not before that.

And this is reason, you need to call onEditDetail() inside Subscribe block as last parameter. there are 3 params to subscribe.

  1. Data which is returned by call,
  2. Error if any occured.
  3. On complete if you wish to do something.

In your case, as 3rd parameter, you have to call onEditDetail method

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

      // 3rd parameter, this is where call is subscribe is completed
      this.onEditDetail(this.id);
    });
}