1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.