预先选择的角度材料下拉列表

时间:2019-11-18 05:45:20

标签: javascript angular typescript angular-material

我在角8中使用角材料。

我需要在dropdwown中预先选择option

我使用此代码:

<mat-select *ngIf="justImage==true">
    <mat-option selected (click)="setExtention('Picture',i)">
    {{ 'ENUM.FILE_TYPE.Picture' | translate }}
    </mat-option>
</mat-select>

,但未在下拉菜单中选择它并禁用它。将其禁用,但不会在下拉列表中显示所选项目。

我该如何解决这个问题??

3 个答案:

答案 0 :(得分:3)

在您的ts文件中,

let options = ['Upcoming', 'Consulted', 'Cancelled'];
let status = 'Consulted';

在您的模板中,

<mat-select [(ngModel)]="status" id="status">
   <mat-option *ngFor="let option of options" [value]="option">
      {{option}}
   </mat-option>
</mat-select>

在ngModel中,状态变量进行双向绑定。因此,这将完成工作。默认情况下,会选择咨询选项。

答案 1 :(得分:2)

尽管答案已经被接受,但是如果您不想使用[(ngModel)]两种方式进行数据绑定并希望分解它,我想给出解决此问题的方法。完整的工作示例可以在此StackBlitz Link

中建立

在您的HTML文件中,我们使用[value]作为默认值设置器。

<mat-select [value]="defaultSelectedOption" id="status" (selectionChange)="onChange($event)">
   <mat-option *ngFor="let food of foods" [value]="food.value">
       {{food.viewValue}}
   </mat-option>
</mat-select>

<br> <br> <div>
              <span> Default selected and changable value is :<strong> {{defaultSelectedOption}}</strong> </span>
          </div>

Class文件是..

defaultSelectedOption = '';
foods: Food[] = [
       {value: 'steak-0', viewValue: 'Steak'},
       {value: 'pizza-1', viewValue: 'Pizza'},
       {value: 'tacos-2', viewValue: 'Tacos'}
];
ngOnInit(){
     this.defaultSelectedOption = this.foods[1].value;
} 
onChange(eventValue){
     this.defaultSelectedOption= eventValue.value;
}

答案 2 :(得分:1)

这里是working Examlpe

 ngOnInit()
 {
     this.selectedValue=this.clients[0];
 }

html

<mat-select [disabled]="true" placeholder="Clients" [(ngModel)]="selectedValue" name="food" (change)="changeClient($event.value)">
  <mat-option *ngFor="let client of clients" [value]="client">
    {{client.clientName}}
  </mat-option>
</mat-select>