繁体   English   中英

ng-select 不发送字段的 id

[英]ng-select is not sending the id of the field

我是 Angular 的新手,我有一个 ng-select 框,我可以从中选择国家/地区,ng-select 选项工作正常,当我提交我选择的选项时,它会提交 id,但是,当我绑定数据时到 ng-select 并提交已经显示它提交名称而不是 id 的数据,我想提交 id,我已经尝试了以下但似乎有问题。 我知道这是非常基本的,但过去 3 个小时我一直在尝试,感谢您的帮助。

company.component.ts

Country: new FormGroup({
    Id: new FormControl('')
  }),

getCountries(){
this.restService.GetAllCountries().subscribe((res: any) => {
  this.countries = res.data.lookups
  })
}

getCompany(){
  this.restService.getCompanyData(this.role).subscribe((res: any) => {
  this.countryLookupId = this.company.country.name_FL;
  //this returns with a string
})
}

公司.组件.html

<ng-select *ngIf="show" formControlName="Id" [(ngModel)]="countryLookupId" class="width">
<ng-option [value]="country.id" *ngFor="let country of countries">{{ country.name_FL }} 
</ng-option>
</ng-select>

我假设有一个countryLookupId: string; 你没有包括的财产?

问题是this.countryLookupId应该是国家 ID,而不是国家名称。 它应该匹配选项值,而不是显示文本。

this.countryLookupId = this.company.country.id;

编辑:

而且您没有正确设置选项:

ng-select 期望您提供一系列项目:

items: [];

ngOnInit(): void {
  // some code to get countries
  //...


  this.items = countries.map.(x => ({ id: country.id, name: country.name_FL }));
}
<ng-select [items]="items"></ng-select>

https://github.com/ng-select/ng-select

编辑:

这就是我认为您的 html 应该是什么样子,假设您现在直接使用 country 数组:

<ng-select *ngIf="countries" [(ngModel)]="countryLookupId" class="width" 
 [items]="countries" bindValue="id" bindLabel="name_FL">
</ng-select>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM