首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Angular 11选择绑定

Angular 11选择绑定
EN

Stack Overflow用户
提问于 2021-04-18 02:25:05
回答 1查看 143关注 0票数 0

我正在使用Angular 11,我正在尝试做一件让我发疯的非常简单的事情。

我有这个country.ts模型对象:

代码语言:javascript
运行
复制
export class Country {
  private id:Number;

  private code?:String;
  private name?:String;

}

我在后端级别有相同的Java Object。现在,我有了一个如下所示的html页面:

代码语言:javascript
运行
复制
<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

代码语言:javascript
运行
复制
......
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值。我也尝试过:

代码语言:javascript
运行
复制
country_onChange(country) {
  console.log(country);
}

在本例中,它打印从DB加载的所有66个对象。你能给我解释一下出什么事了吗?

我忘了添加这样的解决方案:

代码语言:javascript
运行
复制
<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

代码语言:javascript
运行
复制
......
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版本??

EN

回答 1

Stack Overflow用户

发布于 2021-04-19 12:09:49

一张图片胜过千言万语……

谢谢你们。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67141594

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档