At first, add @angualr/material to your angular project.
Command:
ng add @angular/material
Next import the needed material, form modules to your app.modules.ts file like below picture.
Then code for material form select field:
<p class=”mt-5″> select-option-default for material select</p>
<form [formGroup]=”patientCategory”>
<mat-form-field class=”full-width”>
<mat-select placeholder=”Category” [(ngModel)]=’selectedOption’ 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>
<p>{{patientCategory.get(‘patientCategory’).value | json}}</p>
</form>
The above code use [(ngModel)] binding for set default value of selectedOption. In .ts file set default value from the patientCategories[] array to ngOnInit() like below code.
import { Component, OnInit } from ‘@angular/core’;
import { FormBuilder, FormGroup, FormControl, Validators } from ‘@angular/forms’;
@Component({
selector: ‘app-select-option-default’,
templateUrl: ‘./select-option-default.component.html’,
styleUrls: [‘./select-option-default.component.css’]
})
export class SelectOptionDefaultComponent implements OnInit {
patientCategory: FormGroup;
selectedOption: any;
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.selectedOption = this.patientCategories[1];
this.patientCategory = this.fb.group({
patientCategory: [null, Validators.required]
});
const toSelect = this.patientCategories.find(c => c.id == 3);
this.patientCategory.get(‘patientCategory’).setValue(toSelect);
}
}
Hope this will helpful. Please comment below if any queries.