How do I display an ID dynamically using Angular ng-select?

142 views Asked by At

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

   <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>
   </ng-select>

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

Updated:

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

2

There are 2 answers

1
Faizanur Rahman On

You can use safe navigation operator (?) to the templateData

<ng-container *ngFor="let t of this.templateData?.envelopeTemplates"> </ng-container>

If doesn't work, then try to log the data in the template using json pipe

<div> {{ this.templateData?.envelopeTemplates | json }} </div>

If data is not available, then make sure to fetch data inside ngOnInit() method

3
IAmSupreme On

The error comes as a result of trying to access property "value" from an object, From the above code, we are unable to determine what object it is neither are we able to know what action prompts that error.

i suggest u create a ts file in the src folder with the following content export const data = { endPosition: "590", envelopeTemplates: [ { name: "Template One", templateId: "39739845739850" }, { name: "Template Two", templateId: "340982059270" }, { name: "Template Three", templateId: "478979796768" } ] }