2

hi i using the angular material in angular 8 .

i need to pre-selected option in dropdwown .

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

kianoush dortaj
  • 459
  • 2
  • 5
  • 16
  • refer this question https://stackoverflow.com/questions/42148392/angular-material-md-select-default-selected-value or https://stackoverflow.com/questions/50650790/set-default-option-in-mat-select – ram12393 Nov 18 '19 at 05:50
  • #1 Use `ng-container` for `if` condition. #2 Remove `selected` attribute from `mat-option` tag. #3 Refer https://stackoverflow.com/questions/47333171/angular-material-mat-select-not-selecting-default or mentioned by @ram12393 – Sachink Nov 18 '19 at 05:53
  • https://stackoverflow.com/questions/47333171/angular-material-mat-select-not-selecting-default – Saurabh Yadav Nov 18 '19 at 05:59

3 Answers3

3

In your ts file,

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. So, this will do the job. Consulted option will be selected by default.

2

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. Complete working example can be founded in this StackBlitz Link

In your HTML File we use [value] as default value setters.

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

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;
}
Developer
  • 3,309
  • 2
  • 19
  • 23
1

Here is 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>
Chanaka Weerasinghe
  • 5,404
  • 2
  • 26
  • 39