简体   繁体   English

angular 材料中的预选下拉列表

[英]pre selected dropdown in angular material

hi i using the angular material in angular 8.嗨,我在 angular 8 中使用了 angular 材料。

i need to pre-selected option in dropdwown.我需要在 dropdwown 中预先选择option

i using this code:我使用此代码:

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

but it not selected in dropdown and disable that.但它没有在下拉列表中选择并禁用它。 it be disable but it not show selected items in dropdown.它被禁用,但它不会在下拉列表中显示选定的项目。

how can i solve this problem????我怎么解决这个问题????

In your ts file,在您的 ts 文件中,

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

In your template,在您的模板中,

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

In the ngModel, status variable undergoes two-way binding .在 ngModel 中,status 变量是双向绑定的 So, this will do the job.所以,这将完成这项工作。 Consulted option will be selected by default.默认情况下会选择已咨询的选项。

Although, answer is already accepted, but I want to give solution to this problem if you do not want to use [(ngModel)] two way data binding and want to break it down.虽然,答案已经被接受,但是如果您不想使用 [(ngModel)] 两种方式数据绑定并想将其分解,我想为这个问题提供解决方案。 Complete working example can be founded in this StackBlitz Link完整的工作示例可以在这个StackBlitz Link中建立

In your HTML File we use [value] as default value setters.在您的 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 file is.. 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;
}

Here is working Examlpe这是工作示例

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

html 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM