进行选择时,为什么我的材料选择值会被删除?

时间:2019-04-17 20:48:39

标签: angular drop-down-menu angular-reactive-forms

我正在尝试使用Angular Material表单控件。我有一个垫子选择。当我选择一个选项时,这些值将被删除,但这些选项仍会显示。例如,我将表单值转储到屏幕上以观察行为。当我选择一个选项时,屏幕上的转储值会消失,但选项仍显示在下拉菜单中。奇怪的是,如果我用本地选择替换mat-select,那是可行的。关于我做错了什么?

我用原生选择替换了mat-select。可以使用它,但是没有我想要的所有材料设计。我无法通过mat-select使它按文档工作。

// This does not work and clears out when an option is selected
<mat-form-field>
    <mat-label>Pay Category</mat-label>
    <mat-select formControlName="payCategory">
        <mat-option *ngFor="let payCategory of payCategories"
                    [ngValue]="payCategory">
          {{payCategory.description}}
        </mat-option>
    </mat-select>
</mat-form-field>
// This works, but removes some of the material design styling
<mat-form-field>
    <mat-label>Pay Category</mat-label>
    <select matNativeControl
            formControlName="payCategory">
        <option *ngFor="let payCategory of payCategories"
                [ngValue]="payCategory">
          {{payCategory.description}}
        </option>
    </select>
</mat-form-field>
// In case you wish to see the component relevant code, this is the FormControl...
payCategory: new FormControl( this.buildPayCategories() )
// Pull in payCategories for select list from service
  buildPayCategories () {
    this.payCategories = this.timeEntry.payCategories;
    return this.payCategories;
  }

我宁愿使用mat-select来利用材料设计样式,而不是简单地清除选定的值。

// buildPayCategories returns an array of objects. Here is a sample...
0: {payCategoryId: 1, description: "Converted Data ", payType: "Salary", isActive: true}

1 个答案:

答案 0 :(得分:0)

我试图重现您的问题,但对我来说有效。

我使用[ngValue]代替[value]。您可以在Stackblitz上找到here的实用示例,希望对您有所帮助。

修改 根据您的更新:

  public options = [
    {payCategoryId: 1, description: "Converted Data ", payType: "Salary", isActive: true},
    {payCategoryId: 1, description: "Something Else ", payType: "Salary", isActive: true}
  ];
  public selected = this.options[0];
  public payCategory =  new FormControl(this.options)

和模板:

<mat-form-field>
    <mat-label>Pay Category</mat-label>
    <mat-select formControlName="payCategory" [(value)]="selected">
        <mat-option *ngFor="let payCategory of options"
                    [value]="payCategory">
          {{payCategory.description}}
        </mat-option>
    </mat-select>
</mat-form-field>

<p>You selected: {{selected.description}}</p>

这很好,看看!

祝你好运!