Dustin Lee Walker
Dustin Lee Walker

Reputation: 31

Angular Reactive Forms Select Option with pre selected default not working with objects

I have a select option dropdown that gets its options from the back-end via API call and set them. I want to have an option pre selected on page load, but it doesn't seem to work when I set the value to anything. I also tried to pathValue to the form control on page load, that doesn't seem to work either.

HTML

<mat-select id="depositMediaProcessingMode" formControlName="depositMediaProcessingMode"  required >
        <mat-option value="{id: 39, value: 'CASH'}" selected >CASH</mat-option>
        <mat-option  *ngFor="let option of depositMediaProcessingModes"  [value]="option">{{ option.value }}</mat-option>
      </mat-select>

TS

@Input() form: FormGroup;

  this.form.addControl('depositMediaProcessingMode', new FormControl('', [Validators.required])

    this.formService.formOptions.subscribe((options: AssetFeature[]) => {
      this.form.get('depositMediaProcessingMode').patchValue(  {id: 49, value: 'CASH'});

const depositMediaProcessingMode = options.find(option => option.featureType === 'DEPOSIT MEDIA PROCESSING MODE');
      this.depositMediaProcessingModes = (depositMediaProcessingMode ? depositMediaProcessingMode.featureValue : []);
const depositDefault = {id: 39, value: 'CASH'};

Thanks

Upvotes: 1

Views: 1845

Answers (1)

Vasileios Kagklis
Vasileios Kagklis

Reputation: 826

Try:

HTML

<mat-select id="depositMediaProcessingMode" formControlName="depositMediaProcessingMode">
    <mat-option *ngFor="let option of depositMediaProcessingModes" [value]="option">
    {{ option.value }}
    </mat-option>
</mat-select>

TypeScipt:

@Input() form: FormGroup;

this.form.addControl('depositMediaProcessingMode', 
    new FormControl('', [Validators.required])
);

this.formService.formOptions.subscribe((options: AssetFeature[]) => {
    const depositMediaProcessingMode = options.find(option => option.featureType === 'DEPOSIT MEDIA PROCESSING MODE');
    this.depositMediaProcessingModes = (depositMediaProcessingMode ? depositMediaProcessingMode.featureValue : []);
    const defaultOption = this.depositMediaProcessingModes.find(option => option.id === 49);
    this.form.get('depositMediaProcessingMode').setValue(defaultOption);
}

Your default option has to be one of the options rendered in your drop-down, otherwise an empty option will show up as selected.

Upvotes: 1

Related Questions