首页 > 解决方案 > Angular select option field not displaying

问题描述

I'm using Angular 6.

In the component.html file, I'm using FormGroup and the select field is like

<select formControlName="mode_of_payment" type="text" id="input-mode-of-payment" class="form-control">
    <option *ngFor="let mode of modeOfPayments" [(ngValue)]="mode.id" [selected]="mode.id === amountGiven?.mode_of_payment">{{ mode.title }}</option>
</select>

The component.ts file contains

amountGiven: AmountGiven;
updateMoneyForm: FormGroup;
modeOfPayments: Array<ModeOfPaymentData>;

ngOnInit() {

  this._initializeForm();

  // Get mode of payments
  this._getModeOfPayments();
}



private _initializeForm() {
  this.updateMoneyForm = this.formBuilder.group({
    mode_of_payment: new FormControl(),
  });
}

private _getModeOfPayments() {
  this.modeOfPaymentService.list().subscribe(
    res => {
      this.modeOfPayments = res;
      this._setFormValue();
    }
  );
}

private _setFormValue() {
  this.updateMoneyForm.setValue({
    mode_of_payment: this.amountGiven.mode_of_payment,
  });
}

But this is giving select fields like

enter image description here

When I click on the select field, the options are pop-up but even there the selected field is not selected by default and always the first option is having a tick mark.

enter image description here

标签: angularangular6angular-reactive-formsangular-forms

解决方案


您不应该使用该selected指令,反应形式会为您处理:

<select [formControl]="modeOfPayment">
    <option *ngFor="let mode of modeOfPayments"
    [ngValue]="mode.id">{{ mode.title }}</option>
</select>

这是运行代码的链接。


推荐阅读