1

I have filled an array of data(options) by making a call to my database. I console.log the array (dataArray) and it shows that the array has been filled with the expected data. However, when I run the application, the select box shows none of the options from the array and only shows the default option I set in the beginning ('hello'). Any help is appreciated.

select.component.ts:

import { Component, OnInit} from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';

@Component({
    selector: 'app-select',
    templateUrl: './select.component.html',
    styleUrls: ['./select.component.css']
})

export class SelectComponent implements OnInit {

    constructor(private http: HttpClient) {
    }

    dataArray: String[] = ['hello'];
    ngOnInit() {
        const httpParams = new HttpParams().set('cars', 'toyota');
        console.log(this.dataArray);


        let text;
        this.http.get(`http://localhost/scheduler/parse.php`, { params: httpParams, responseType: 'text' }).subscribe(function (response) {
            text = response;
            console.log(text);
            this.dataArray = JSON.parse(text.replace(/'/g, '"'));
            console.log(this.dataArray);
        });
    }

}

select.component.html:

<mat-card style="margin-top: 25px">
  <mat-form-field>
    <mat-select placeholder="Cars">
      <mat-option *ngFor="let data of dataArray" [value]="data">
        {{data}}
      </mat-option>
    </mat-select>
  </mat-form-field>
</mat-card>
Krish
  • 11
  • 1
  • How does `dataArray` look like when you console.log it? Is it an array first of all? Maybe stupid question, but just to be sure :P – AT82 Feb 09 '19 at 17:29
  • Yes, dataArray comes out as an array when I console.log it. The text variable holds the string representation of the array. – Krish Feb 09 '19 at 17:33
  • Use an arrow function as the callback: `subscribe((response) => { ... })`. – ConnorsFan Feb 09 '19 at 17:37
  • Just saw it too @ConnorsFan . You were faster! :D – AT82 Feb 09 '19 at 17:37
  • Wow, I never knew this worked like that in Angular. I spent all of yesterday trying to figure this out and it was this. I don't know if I can upvote comments, but thank you so much ConnorsFan and AJT_82 for the help! – Krish Feb 09 '19 at 17:59

0 Answers0