【发布时间】:2019-01-25 15:08:29
【问题描述】:
最近我开始工作 Angular 6。我在为 Select 元素设置默认值时发现问题。事实上,我正在寻找基于对象的 Select 元素。这是我的 HTML
.html 文件:
<div>
Select The Country
<select [(ngModel)]="SelectedCountry3">
<option *ngFor="let country of countryList" [ngValue]="country">{{country.CountryName}}</option>
</select>
</div>
<div>
Selected Coutry is : <b>{{SelectedCountry3.CountryName}} -- {{SelectedCountry3.Id}} </b>
</div>
.ts 文件:
import { Component } from '@angular/core';
@Component({
selector: 'app-angular-drop-down',
templateUrl: './angular-drop-down.component.html',
styleUrls: ['./angular-drop-down.component.css']
})
export class AngularDropDownComponent {
countryList: CountryM[];
SelectedCountry3: CountryM;
constructor() {
this.countryList = [
{ Id: 1, CountryName: "Bangladesh" },
{ Id: 2, CountryName: "India" },
{ Id: 3, CountryName: "Pakistan" },
{ Id: 4, CountryName: "Srilanka" },
{ Id: 5, CountryName: "Mayenmar" },
{ Id: 6, CountryName: "Bhutan" },
{ Id: 10, CountryName: "Maldivs" }
];
this.SelectedCountry3 = { Id: 2, CountryName: "India" };
}
trackByFn(index, item) {
return item.Id; // or item.id
}
}
interface CountryM {
Id: number;
CountryName: string;
}
问题是当从 Select 元素中选择值时,我得到了 Country 对象,但我无法通过 Select 设置默认值 国家对象。在 AngularJS 中它可以工作。但在 Angular 中却没有。有人知道为什么吗?还是我错过了什么?
【问题讨论】: