Angular 5 + Material Design: <mat-select> how to set the default value?

 <mat-form-field>
      <mat-select [formControl]="form.controls['defaultCategory']" [(ngModel)]="resource.categoryName" >
        <mat-option *ngFor="let category of categories | async" [value]="category._id" >
          {{ category.name }}
        </mat-option>
      </mat-select>
 </mat-form-field>

I tried many things. The docs, some bug-reports on github still not solve my Problem.

I only want do preset a default value...

The default value is stored a variable named: resource.categoryName. The options comes from a collection from mongodb and these are stored in categories[].

This picture shows the closed mat-select (no default value shown, but it should...)

opened mat-select

Here is my .ts. The important line is "this.resource.categoryName = this.subdoc['name'];". There i set the "resource.categoryName. If i try to console.log(this.resource.categoryName), then i get the name of the category...

Creating a variable in the .ts and be sure its a string. After that declare the variable with the ID of the default Category. (in my case it only worked with the ID, not with the simple name) - Thanks to Simeon, Hamid and other Threads about this problem.

Upvotes: 4

Views: 3967

Answers (1)

Simeon Nakov
Simeon Nakov

Reputation: 1048

I can't see your component file but the problem might be that your resource.categoryName doesn't have a value set on initialization of the component. Try setting it manually in your *.component.ts file.

Upvotes: 1

Related Questions