【问题标题】:preselecting a value in angular material dropdown在角度材料下拉列表中预选一个值
【发布时间】:2021-10-09 02:23:33
【问题描述】:

我是 Angular 的新手。在 HTML 表单上,用户可以选择下拉列表值,我需要在角度表中显示该值。我这样显示该值:

<ng-container matColumnDef="PaymentMethodName">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Payment Method</mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.PaymentMethodName}} </mat-cell>
  </ng-container>

现在,我被要求在具有预选值的表格中显示整个下拉列表,所以我尝试这样做:

ng-container matColumnDef="PaymentMethodName">
                  <mat-header-cell *matHeaderCellDef mat-sort-header> Payment Method</mat-header-cell>
                  <mat-cell *matCellDef="let element">
                    <mat-form-field floatLabel="never" appearance="outline" [style.width.px]=150>
                      <mat-select placeholder="Payment Type" [(ngModel)]="SelectedMailItem.PaymentMethod" name="paymentType" (change)="ClearAmount(SelectedMailItem)">
                        <mat-option *ngFor="let paymentType of Picklist.PaymentMethods" [value]="paymentType">
                          {{paymentType.Name}}
                        </mat-option>
                      </mat-select>
                    </mat-form-field>

                  </mat-cell>
                </ng-container>

下拉列表显示在表格中,但我不知道如何在下拉列表中显示选择的值。之前我只是在用这个声明来证明它的价值:

element.PaymentMethodName

我们将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    要从下拉列表中选择初始项目,请使用以下语法:

    <mat-select [(value)]="mySelection">
    ..
    

    在您的 TS 代码中,选择数组项如下:

    mySelection = this.myList[1].value; 
    

    myList 声明如下(或使用组件中预先存在的数据源):

    myList: MyPaymentList[] = [
        {value: '1', viewValue: 'Cash'},
        {value: '2', viewValue: 'Credit'},
        {value: '3', viewValue: 'Cheque'}
    ];
    

    这将使用 Cheque 项初始化下拉菜单。

    在您的表格示例中,只需将表格行 element.PaymentMethodName 中的值作为 mat-select 中的初始值传递,如上所示。

    然后您的下拉列表声明为:

    <mat-select placeholder="Payment Type" 
        [(ngModel)]="SelectedMailItem.PaymentMethod" name="paymentType" 
        (change)="ClearAmount(SelectedMailItem)"
        [(value)]="element.PaymentMethodName">
    

    【讨论】:

      猜你喜欢
      • 2020-03-13
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多