【发布时间】:2021-07-12 10:42:17
【问题描述】:
我正在使用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 版本??
【问题讨论】:
-
您希望从
(change)事件中发出什么?您将控件绑定到一个由国家组成的本地州。然后,您通过遍历该数组来填充下拉列表。并且在更改时,您正在传递该数组备份?可能会出现混淆,因为您的选项是Country类型,您将模型链接到Country[]类型(这是允许显示您可以选择的对象的相同列表)。尝试将结果与定义选项列表的数据分开。 -
你试过
[value]吗? -
在您上面的代码添加中,您有一个错字(您的 html 中的
filterCountry,与您的 .ts 文件中的filteredCountry)。你能确认这只是在这篇文章中,还是在你的代码中? -
Angular 实际上是一个相当可靠且设计良好的框架。你可以在这里找到文档:angular.io/api/forms/SelectControlValueAccessor
-
我认为您的问题可能是在模板中重复使用相同的变量名。例如,您的 ngModel 绑定标记为
country,而您的 ngFor 也在尝试循环通过country我做了一个最小的堆栈闪电战来演示您的用例 stackblitz.com/edit/angular-ivy-r9kuvv?file=src/app/…
标签: angular typescript select binding