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>
组件:
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);
}
);
}
这是我的代码我想选择这个api中的值,但我没有得到任何值,请帮我如何绑定它
在我的api中我有'state'
名称我希望下拉列表中的值如何获取
答案 0 :(得分:1)
将myBooks数组声明为:
myBook : any[]=[]
并传递数据的值:
this.myBook = data
它会起作用!
答案 1 :(得分:0)
您正在使用被选为ngModel。您应该确定需要选择的值。
在您的代码中,您指定的是null。
答案 2 :(得分:0)
问题是您将myBooks: string [];
声明为字符串数组。稍后在*ngFor
循环中,您尝试将其作为对象book.state
因此,请稍后声明myBooks: any [] = [];
确保api正在响应您期望的数据。
我希望这有帮助,