我正在使用Angular 11,我正在尝试做一件让我发疯的非常简单的事情。
我有这个country.ts模型对象:
export class Country {
private id:Number;
private code?:String;
private name?:String;}
我在后端级别有相同的Java Object。现在,我有了一个如下所示的html页面:
<div class="country-select">
<select [(ngModel)]="country" class="form-select form-select-sm" (change)="country_onChange(country)">
<option [ngValue] = 0> SELECT COUNTRY</option>
<option *ngFor="let c of country" [ngValue]="c">{{c.id}}</option>
</select>
</div>和上面页面的匹配.ts:
......
constructor(
private airpollService: AirpollService,
) { }
country: Country[];
ngOnInit(): void {
this.airpollService.dataList(this.page).subscribe(success => {
this.airpoll = success;
});
country_onChange(selectedCountry:any) {
console.log(selectedCountry);
}后端调用运行良好..在我的html页面中,我看到我的select被正确加载,但是当我选择一个值并触发country_onChange()事件时,它会输出undefined。
我已经尝试了所有方法,将整个对象放入[ngValue]中,只放入id值。我也尝试过:
country_onChange(country) {
console.log(country);
}在本例中,它打印从DB加载的所有66个对象。你能给我解释一下出什么事了吗?
我忘了添加这样的解决方案:
<select
id="filterCountry"
[(ngModel)]="filterCountry"
name="filterCountry"
class="form-select form-select-sm"
(change)="country_onChange()"> // I can put everuthing here, nothing works
<option *ngFor="let c of country" [ngValue]="c">{{c.id}}</option>
</select>到我的.ts
......
constructor(
private airpollService: AirpollService,
) { }
country: Country[];
filterCountry: Country; // or any, nothing change
ngOnInit(): void {
this.airpollService.country().subscribe(success => {
this.country = success;
this.filterCountry = this.country[0]; // I have seen this on a example, sound pretty stupid
});
country_onChange() {.
console.log(this.filterCountry.id); // print always 1..
}@tmtplayer我已经在不同的帖子上读到了所有这些东西。但根据版本的不同,有几种方法可以做到这一点。
对不起是打字错误,我已经改正了。在我的代码中,两端都有filterCountry,但无法工作。我用过value,但没有用过[value]。我会尽力让你知道的。这真的很令人惊讶,因为我有和我一样的工作代码,使用以前版本的Angular (Angular 7)可以工作。这真是一门差劲的语言!互联网上是否存在此语言文档的11版本??
发布于 2021-04-19 12:09:49
一张图片胜过千言万语……

谢谢你们。
https://stackoverflow.com/questions/67141594
复制相似问题