Mat-select 输入组合对象

Mat-select input composed object

我正在努力将组合值输入 select。假设我们的对象只包含一个 ID 和一个 name,通常使用 select 的方法是:

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

现在要提供一个值,我发现 this working example in the documentation 只是将 [(value)] 选项添加到 mat-select 标记中,但是由于我们在这里得到了一个组合对象,所以它不起作用任何人。

知道如何解决这个问题吗?非常感谢 ! 凯夫'

看看这个: 打字稿:

      /** @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>

当您添加行 <mat-select [(value)]="selectedOptionName"> 时,它将“收集”此行 <mat-option *ngFor="let myOption of myOptions" [value]="actualValueGoesHere"> 中进入 [value] 的所有值。 您可以随心所欲地使用该值。

要设置初始值,只需设置 selectedOption = this.myOptions[2](或者应该是第一个选择)