0

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?

4
  • what is the initial value of ngModel=dashboard? Commented Mar 3, 2020 at 3:44
  • I have to set that value. I don't know how to set. Commented Mar 3, 2020 at 4:01
  • can i see your component code? Commented Mar 3, 2020 at 4:02
  • after loading data in CLIENT_STATUS then you have to assign id of first index to dashboard. Commented Mar 3, 2020 at 4:15

2 Answers 2

2

.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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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';

4 Comments

I am rendering data from backend. so in that case how to set default value?
When you get data from backend you should initialize selected property with the value recovered
I did initialising the value. But still i am not able to achieve that.
could you provide your ts file please

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.