chethu
chethu

Reputation: 353

angular 4 setting dropdown option values received from api

html:

<div *ngIf="myBooks">
    <mat-select [(ngModel)]="selected">
      <mat-option *ngFor="let book of myBooks" name="state">{{book.state}}</mat-option>
    </mat-select>
 <p>{{ selected }}</p>
</div>

component:

import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material';
import {Component, Inject} from '@angular/core';
import {DataService} from '../../create/createservice';
import {FormControl, Validators} from '@angular/forms';
import {State} from '../../create/model';
import {City} from '../../create/model2';
import { HttpClient } from '@angular/common/http';
import { HttpErrorResponse } from '@angular/common/http/src/response';

@Component({
selector: 'app-add.dialog',
templateUrl: '../../dialogs/cityadd/add.dialog.html',
styleUrls: ['../../dialogs/cityadd/add.dialog.css']
})

export class AddDialogComponent1 {

constructor(public dialogRef: MatDialogRef<AddDialogComponent1>,
          @Inject(MAT_DIALOG_DATA) public data1: City,
          public dataService: DataService,private httpService:HttpClient) { 
  }

myBooks: string [];
selected = null;

formControl = new FormControl('', [
Validators.required
// Validators.email,
]);

states: string[];
city:string[];


 ngOnInit () {
  this.httpService.get('api/state-city').subscribe(
    data => {
      this.myBooks = data as string [];     // FILL THE ARRAY WITH DATA.
    },
    (err: HttpErrorResponse) => {
      console.log (err.message);
    }
  );
 }

This is my code i want to select values which is there is in this api but i am not getting any values please help me how to bind it

in my api i have 'state' name i want that values in the dropdown list how to get it

Upvotes: 1

Views: 1564

Answers (3)

bereket gebredingle
bereket gebredingle

Reputation: 13016

The problem is you declare myBooks: string []; as array of strings. And later in your *ngFor loop you tried to access them as an array of object book.state

So declare myBooks: any [] = []; later make sure the api is responding the data u r expecting.

I hope this helps,

Upvotes: 0

Biju Maharjan
Biju Maharjan

Reputation: 449

Declare array of myBooks as:

myBook : any[]=[]

and pass value of data on that :

this.myBook = data

It will work!

Upvotes: 2

Lakshmi Prasanna
Lakshmi Prasanna

Reputation: 456

you are using selected as a ngModel. You should assing the value whihc need to be selected.

here in your code you are assigning a null.

Upvotes: 0

Related Questions