【问题标题】:Mat-select input composed objectMat-select 输入组合对象
【发布时间】:2021-02-22 21:18:10
【问题描述】:

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

<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 只是在 mat-select 标记中添加了一个 [(value)] 选项,但是由于我们在这里得到了一个组合对象,所以它不再起作用了。

关于如何解决这个问题的任何想法?非常感谢 ! 凯夫'

【问题讨论】:

    标签: angular typescript drop-down-menu angular-material angular11


    【解决方案1】:

    看看这个: 打字稿:

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

    当您添加&lt;mat-select [(value)]="selectedOptionName"&gt; 行时,它将“收集”该行 &lt;mat-option *ngFor="let myOption of myOptions" [value]="actualValueGoesHere"&gt; 中的[值] 中的任何值。 您可以随意使用该值。

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

    【讨论】:

    • 好吧,我尝试了你在this stackblitz 中的意思,但它没有在选择中输入值
    • 我不明白你的意思。你期望发生什么?
    • 我的整个问题是如何在选择中输入值以显示默认值并允许用户在不更改下拉值的情况下点击“保存”按钮,如果对他来说可以的话!跨度>
    • 例如如何在页面加载时显示选项 2
    • 我已经编辑了答案。你只需要在你的 .ts 中设置 selectedOption stackblitz.com/edit/angular-6lwijf-vrh46b?file=src/app/…
    猜你喜欢
    • 2019-07-10
    • 2018-09-04
    • 1970-01-01
    • 2021-12-24
    • 2020-03-01
    • 2018-11-23
    • 2019-08-09
    • 1970-01-01
    • 2019-08-07
    相关资源
    最近更新 更多