Reputation: 91
I want 0th index to to be selected as default in dropdown list angular material.
<mat-form-field>
<mat-select
name="dashboard"
(selectionChange)="showDashboard(dashboard)"
[(ngModel)]="dashboard"
[(value)]="selected"
>
<mat-option *ngFor="let status of CLIENT_STATUS" [value]="status.id">
{{ status.name }}
</mat-option>
</mat-select>
</mat-form-field>
Can anyone please tell what has to be done to set the default value on loading of page?
Upvotes: 0
Views: 5672
Reputation: 21
.html file
<form [formGroup]="patientCategory">
<mat-form-field class="full-width">
<mat-select placeholder="Category" formControlName="patientCategory">
<mat-option>--</mat-option>
<mat-option *ngFor="let category of patientCategories" [value]="category">
{{category.name}} - {{category.description}}
</mat-option>
</mat-select>
</mat-form-field>
</form>
.ts file
export class TableBasicExample {
patientCategory: FormGroup;
patientCategories=[{
id:1,
name:'name 1',
description:'description 1'
},{
id:2,
name:'name 2',
description:'description 2'
},{
id:3,
name:'name 3',
description:'description 3'
}]
constructor(private fb: FormBuilder){}
ngOnInit() {
this.patientCategory = this.fb.group({
patientCategory: [null, Validators.required]
});
const toSelect = this.patientCategories.find(c => c.id == 3);
this.patientCategory.get('patientCategory').setValue(toSelect);
}
}
Upvotes: 2
Reputation: 650
Here an example: HTML file:
<mat-form-field>
<mat-label>Test</mat-label>
<mat-select [(value)]="selected">
<mat-option value="option1">Option 1</mat-option>
<mat-option value="option2">Option 2</mat-option>
</mat-select>
</mat-form-field>
and in your TS file set the default value:
selected = 'option1';
Upvotes: 1