【问题标题】:Set a default value for Angular chain dropdown为 Angular 链下拉菜单设置默认值
【发布时间】:2019-12-28 00:43:39
【问题描述】:

我在 ID 中有 JSON 国家/地区,我想要将 defeulat 值设置为选中,这里是我的选择代码:

<select (change)="onNationalitySelected($event.target.value)" id="nationality" formControlName="nationality">
                <option value=""> {{'messages.dropdownselect' | translate}} </option>
                <option *ngFor="let country of countries" [value]="country.id" [selected]="country.id == '100'" >
                  {{ country.name }}
                </option>
              </select>

.ts 文件

  onNationalitySelected(nationalityId: number) {
    this.customer.coid = nationalityId;
    this.customer.nationality = this.countries.filter(
      c => (c.id == nationalityId)
    )[0].name;

我尝试将国家/地区的默认值设置为 100,但它不起作用,保存到数据库后该值仍然为空。

感谢任何cmets。

【问题讨论】:

  • 不确定我是否理解您的问题。如果问题是“如何预先选择一个选项”,那么这个问题已经被问了很多,答案总是一样的:唯一的真理就是模型。不是景色。所以删除 [selected]="...",并确保在您的 TypeScript 代码中,国籍表单控件的值是 === 选择显示的国家/地区之一的 ID。跨度>
  • 嗨@JBNizet,感谢您的评论,在 ngModel 中进行了很多尝试,等等。但没有运气。我想要的是预先填充选项框的默认值而不先选择。如果你不介意,你能分享一个链接吗?我试图找到它一整天:(
  • 您使用的是响应式表单,而不是模板驱动的表单。所以 ngModel 是无关紧要的。同样,在 TypeScript 代码中,表单控件的值必须设置为国家 ID 之一。发布您的 TypeScript 代码。这就是它必须发生的地方。
  • 对不起@JBNizet,我不明白,顺便谢谢

标签: angular dropdown


【解决方案1】:

ts

// Let's use FormGroup so we can add a control/default
countryForm: FormGroup;

// define our countries data
countries = [{
 id: '100',
 name: 'USA',
 code: 'USD'
},
{
 id: '200',
 name: 'Canada',
 code: 'CAD'
},
{
 id: '300',
 name: 'UK',
 code: 'GBP'
}];

constructor(private fb: FormBuilder) {}

ngOnInit() {
 // set country code 100 as default
 this.countryForm = this.fb.group({
  countryControl: [this.countries[0].id]
 });
}

html

// ngValue allows us to use an object for default value assignment
<option [ngValue]="country.id" *ngFor="let country of countries">{{country.name}}</option>

我对@9​​87654323@ 有点不确定,如果它不起作用,试试这个:countryControl: [this.countries[0]]

告诉我进展如何!

【讨论】:

  • 耶!!很高兴能提供帮助。
猜你喜欢
  • 1970-01-01
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 2019-09-25
  • 1970-01-01
  • 2021-04-13
  • 2021-08-03
  • 2018-09-29
相关资源
最近更新 更多