【问题标题】:pre selected dropdown in angular material角度材料中的预选下拉菜单
【发布时间】:2020-03-13 11:19:15
【问题描述】:
你好,我使用 angular 8 中的 angular 材料。
我需要在 dropdwown 中预先选择option。
我使用此代码:
<mat-select *ngIf="justImage==true">
<mat-option selected (click)="setExtention('Picture',i)">
{{ 'ENUM.FILE_TYPE.Picture' | translate }}
</mat-option>
</mat-select>
但它没有在下拉列表中选择并禁用它。它被禁用,但它不会在下拉列表中显示选定的项目。
我该如何解决这个问题????
【问题讨论】:
标签:
javascript
angular
typescript
angular-material
【解决方案1】:
在你的 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 中,status 变量经历了双向绑定。所以,这将完成这项工作。 咨询选项将默认被选中。
【解决方案2】:
这里是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>
【解决方案3】:
虽然答案已经被接受,但是如果您不想使用 [(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>
类文件是..
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;
}