只有一个选项时,Angular会自动选择Mat-Select

时间:2019-01-03 23:05:24

标签: javascript arrays angular select angular6

如果mat-select中只有一个选项,我需要设置默认值。否则,请保留黑色以供用户选择。 这是我的HTML代码

<mat-form-field>
<mat-select (selectionChange)="CompartSelected($event, element, cmpart)" disableRipple [value]="element.Compart.Id" name="cmpart" >
  <mat-option *ngIf="getAvailableCompartList(element.Compart.CompartType.Id).length > 1" value="">-- Please Select an Option --</mat-option>
  <mat-option *ngFor="let cmpart of getAvailableCompartList(element.Compart.CompartType.Id)" title="{{Translate(cmpart.CompartNote)}}" 
      [value]="cmpart.Id">{{cmpart.CompartTitle}}
  </mat-option>

根据@Sean解决方案,我已经更新了代码。但是,它不会将值设置为Mat-select。 我已经附上了一些垫子选择的照片。

enter image description here

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

编辑:对不起-被误解了。如果只有一个选项(默认行为),则要选择该值;否则,当有2个以上选项可用时,请留空。仅当ngFor表达式返回多个项目时,才在ngFor之外添加其他mat-option。

<mat-form-field>
    <mat-select (selectionChange)="CompartSelected($event, element, cmpart)" disableRipple [value]="element.Compart.Id" name="cmpart" >
      <mat-option *ngIf="getAvailableCompartList(element.Compart.CompartType.Id).length > 1" value="">-- Please Select an Option --</mat-option>
      <mat-option *ngFor="let cmpart of getAvailableCompartList(element.Compart.CompartType.Id)" title="{{Translate(cmpart.CompartNote)}}" 
          [value]="cmpart.Id">{{cmpart.CompartTitle}}
      </mat-option>
   </mat-select>
</mat-form-field> 

您可以通过在组件内部放置对getAvailableCompartList的函数调用来进行一些清理,以免在呈现模板时对函数进行两次评估。

答案 1 :(得分:1)

以防有人仍在寻找提示。 通常,当您选择的大小不同时,表示它来自可观察的对象。 因此,您可以这样做:

打字稿代码:

//HERE IS THE FUNCTION THAT LOADS YOUR OPTIONS. IN THIS CASE 'val' IS MY API RETURN.
//IN CASE SIZE IS 1, PASS THE FIRST VALUE TO YOUR VARIABLE MODEL.

        loadParameter(){
                this.service.getParameters().subscribe((val: any) => {             
                  this.parameters = val; 
                  if (val.length == 1) {
                    this.selectedParameter = val[0].ParameterId;
                  }
                });
    }

----------------------------------------------------------------------------
Here the front code:
     
            <mat-label>Example</mat-label>
            <mat-select [(ngModel)]="selectedParameter">
                <mat-option *ngFor="let parameter of parameters" [value]="parameter.ParameterId">{{parameter.ParameterValue}}</mat-option>
            </mat-select>    
------------------------------------------------------------------------
相关问题