0
votes

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

3

3 Answers

1
votes

You should not use the selected directive, the reactive form will take care of that for you :

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

Here is a link to a running code.

0
votes

The problem here is that chosen a new option will not cause any changes, the TS (type script) attributes.

You need to implement the onchange action on the select tag as such.

<select formControlName="mode_of_payment" type="text" id="input-mode-of-payment" 
 class="form-control" (change)="someFunction($event)">

    <option *ngFor="let mode of modeOfPayments" [(ngValue)]="mode.id" 
    [selected]="mode.id === amountGiven?.mode_of_payment">{{ mode.title }}</option>

</select>

After which you will need to implement the function such as it changes the default selected value.

0
votes

Chances are it's from your css. Remove the form-control class on the select field and it's gonna display. You can write your custom css for the select field.