Search code examples
angulartypescriptdrop-down-menuangular-materialangular11

Mat-select input composed object


I am struggling to input a composed value into a select. Let's say our object only contain an ID and a name, an usual way to have a working select would be to do :

<mat-form-field>
   <mat-label>Placeholder</mat-label>
   <mat-select>
      <mat-option *ngFor="let i of fooCollection" [value]="i.id">
         {{i.name}}
      </mat-option>
   </mat-select>
</mat-form-field>

Now to feed a value, I found this working example in the documentation which simply add a [(value)] option into the mat-select tag, but since we got a composed object here it doesn't work anymre.

Any idea on how to solve this ? Many thanks ! Kev'


Solution

  • Have a look at this: Typescript:

          /** @title Select with 2-way value binding */
      @Component({
        selector: 'select-value-binding-example',
        templateUrl: 'select-value-binding-example.html',
      })
      export class SelectValueBindingExample {
    
      myOptions = [
        new MyOptions('name1','description1' ),
        new MyOptions('name2','description2' ),
        new MyOptions('name3','description3' ),
      ]
    
    
      selectedOption = this.myOptions[2]
    
      }//Cls
    
      //-----------------------------------------------------//
    
      class MyOptions{
        constructor(
          public name:string,
          public description:string
        ){}
      }
    

    Html:

              <mat-form-field appearance="fill">
          <mat-label>Select an option</mat-label>
          <mat-select [(value)]="selectedOption">
            <mat-option *ngFor="let myOption of myOptions" [value]="myOption">
              {{myOption.description}}
            </mat-option>
          </mat-select>
        </mat-form-field>
    
        <p>You selected: {{selectedOption|json}}</p>
    

    When you add the line <mat-select [(value)]="selectedOptionName"> it will "collect" what ever value went into the [value] in this line <mat-option *ngFor="let myOption of myOptions" [value]="actualValueGoesHere">. And the you can uise the value however you like.

    To set an initial value just set selectedOption = this.myOptions[2] (or what ever the first choice shouold be)