Using Angular ng-select, How can I display the id and name from a JSON response in the select option?

120 views Asked by At

I'm using ng-select to display items from an API.

{
  "endPosition": "590",
   "envelopeTemplates": [
  {
  "name": "Template One",
  "templateId": "39739845739850"
  },
  {
  "name": "Template Two",
  "templateId": "340982059270"
  },
  {
  "name": "Template Three",
  "templateId": "478979796768"
  }
 ]
}

This is how I am displaying the items in a drop-down using ng-select.

<ng-select placeholder="Select Template" #templates (change)="onChange()">
  <ng-container *ngFor ="let t of templateData.envelopeTemplates">
    <ng-container *ngIf="t.name && t.templateId">
      <ng-option value="{{t.templateId}}">{{t.name}}</ng-option>
    </ng-container>
  </ng-container>

In my code you can see that I'm pulling the name from the request but I need to also display the id in the value. When I run this I get this error, main.js:36218 ERROR TypeError: Cannot read properties of undefined (reading 'value')

I need to have the templateID bind to the value cause when a user selects an option the id is used to send a request to the API to get more data on that template. Everything else is working fine I just am stuck on this issue. This is in a reactive form as well. Here is the method.

getTemplates(){
 this.templateFieldService.getTemplate().subscribe((temp: Template) => {
  if(temp){
    this.templateData = temp;
    this.templateData.envelopeTemplates.forEach(temp =>{
    this.tempData?.push(temp.name);
    this.tempId?.push(temp.templateId);
  })
 }
  console.log(this.templateData)
 });

I've created a StackBlitz to display what I am talking about. StackBlitz

1

There are 1 answers

0
oksd On BEST ANSWER

Change FormGroup

  envelopeRequest = this.fb.group({
    name: '',
    email: '',
    optionRequest: null,
  });

Add formControlName

<form [formGroup]="envelopeRequest">
  <div>
    <ng-select
      placeholder="Select Template"
      #templates
      (change)="onChange()"
      formControlName="optionRequest"
    >
      <ng-container *ngFor="let t of templateData.envelopeTemplates">
        <ng-container *ngIf="t.name && t.templateId">
          <ng-option value="{{t.templateId}}">{{t.name}}</ng-option>
        </ng-container>
      </ng-container>
    </ng-select>
  </div>
</form>

Access to the value of the FormControl

  onChange() {
    console.log(this.envelopeRequest.get('optionRequest')?.value);
  }