【问题标题】:Angular Reactive Forms Select Option with pre selected default not working with objectsAngular Reactive Forms Select Option 预选默认值不适用于对象
【发布时间】:2020-12-16 01:54:29
【问题描述】:

我有一个选择选项下拉菜单,它通过 API 调用从后端获取其选项并设置它们。 我想在页面加载时预先选择一个选项,但是当我将值设置为任何值时它似乎不起作用。 我还尝试在页面加载时将 pathValue 设置为表单控件,但这似乎也不起作用。

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'};

谢谢

【问题讨论】:

    标签: angular angular-reactive-forms


    【解决方案1】:

    试试:

    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);
    }
    

    您的默认选项必须是下拉菜单中呈现的选项之一,否则将显示一个空选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-22
      • 2020-12-28
      • 2021-10-05
      • 2018-04-11
      • 2019-02-22
      • 1970-01-01
      • 2019-07-19
      • 2018-10-14
      相关资源
      最近更新 更多