Search code examples
angularformsngfor

Grabbing a value from ngFor to use as a parameter in a nested form


I have an array of terms I'm looping over to display some dictionary results, these results have links that are related to them. I have a small form per dictionary term that fires off a lambda function to run a stored procedure that adds a link. One of the parameters to add a link is the current dictionary terms ID. As far as I can tell from my Java error on the lambda side the function isn't getting the term ID sent over, so I feel like I'm doing something wrong when trying to grab the ID on the front-end.

Template with form

<ul>
  <li *ngFor="let term of terms">
      {{ term.term }} - {{ term.def }}
      <ul>
        <li *ngFor="let link of term.links">
          {{ link.name }} - {{ link.url }}
        </li>
      </ul>
      <div class="add-link">
        <form [formGroup]="addRelatedLinkForm" (ngSubmit)="addRelatedLinkSubmit(term.id, addRelatedLinkForm)">
          <input id="name" formControlName="name" type="text" placeholder="Link name">
          <input id="url" formControlName="url" type="text" placeholder="URL">
          <button type="submit">Add Related Link</button>
        </form>
      </div>
  </li>
</ul>

Add Related Link service

addRelatedLink(token: String, id: Number, link: Link): Observable<any> {
    this.link_url = "http://localhost:4200/link";
    let body = {
      "name": link.name,
      "url": link.url,
      "term_id": id
    }
    const headers = new HttpHeaders({
      'Authorization': 'Bearer ' + token,
      'Content-Type': 'application/json'
    });
    return this.http.post<any>(
      this.link_url,
      body,
      {
        headers: headers
      }
    )
  }
}

Component function

addRelatedLinkForm = this.formBuilder.group({
    name: '',
    url: '',
    term_id: ''
  })


addRelatedLinkSubmit(id: number): void {
    this.termsService.getAWSToken().subscribe(token => {
      this.termsService.addRelatedLink(token.access_token, id, this.addRelatedLinkForm.value).subscribe(data => {
        console.log(data);
      });
    });
  }

Any point in the right direction is greatly appreciated!

EDIT

Problem solved, Roya made me realize a few things were off, after debugging, I noticed my data being sent over the wire was correct, I just wasn't matching some Java parameters on the Lambda side.


Solution

  • There is different between method definition and call!

    where you call the method at template addRelatedLinkSubmit(term.id, addRelatedLinkForm) it has two arguments and in the component where you defined the method addRelatedLinkSubmit(id: number): void there is one parameter that it accepts.