0

Problem : Populating JSON values (which is gathered over the REST api) into Select statement?

team.component.html

<mat-select placeholder="Select Name" [(ngModel)]="name">
  <mat-option *ngFor="let currentName of nameValuesArray" [value]='currentName.name'>
    {{currentName.name}}
  </mat-option>
</mat-select>

team.component.ts

export class UpdateTeamRosterComponent implements OnInit {

  nameValuesArray;
  name;

  constructor(private fetchData : FetchdataService) { }

  ngOnInit() {
    console.log('ngOnIt called');
    this.nameValuesArray = this.fetchData.getAllEmployeeNames('DCP').subscribe(data=>{
      this.nameValuesArray = JSON.stringify(data);
    });

  }
}

ERROR

  UpdateTeamRosterComponent.html:1 ERROR Error: Cannot find a differ supporting object '[{"name":"Ajith"},{"name":"Anand"},{"name":"Bharath"}]' of type 'string'. NgFor only supports binding to Iterables such as Arrays.
      at NgForOf.push../node_modules/@angular/common/fesm5/common.js.NgForOf.ngDoCheck (common.js:3161)
      at checkAndUpdateDirectiveInline (core.js:18623)
      at checkAndUpdateNodeInline (core.js:19884)
      at checkAndUpdateNode (core.js:19846)
      at debugCheckAndUpdateNode (core.js:20480)
      at debugCheckDirectivesFn (core.js:20440)
      at Object.eval [as updateDirectives] (UpdateTeamRosterComponent.html:2)
      at Object.debugUpdateDirectives [as updateDirectives] (core.js:20432)
      at checkAndUpdateView (core.js:19828)
      at callViewAction (core.js:20069)

Data is fetching properly from the server Problem is rendering the data on to select

1
  • You have assigned the return of this.fetchDatagetAllEmployeeNames('DCP').subscribe to the nameValuesArray variable (this value is an instance of subscription). Then you have assigned the value of the response also to the same object. Both are different things. You can use *ngFor on the data, not on the subscription. Commented Jan 11, 2019 at 13:05

2 Answers 2

1

Assign the observable to the field.

this.nameValuesArray = this.fetchData.getAllEmployeeNames('DCP');

Then use async pipe in the template:

<mat-option *ngFor="let currentName of nameValuesArray | async" [value]='currentName.name'>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your concern
It subscribes to the observable from template. And when the component is destroyed, it automatically unsubscribes.
1

Do not use JSON.stringify , it will convert your array to string, change it as follows

this.nameValuesArray = data;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.