rimi
rimi

Reputation: 775

preselecting a value in angular material dropdown

I am new to angular. On the HTML form, Users can select the drop down list value and I need to display that value in a angular table. I am displaying that value like so:

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

Now, I am asked to display the entire drop down in the table that has preselected value so I tried doing this:

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>

Drop down is showing in the table, but I dont know how to show the sleected value in the drop down. I was shoing just the value with this statement before:

element.PaymentMethodName

any help will be appreciated.

Upvotes: 2

Views: 933

Answers (1)

Andrew Halil
Andrew Halil

Reputation: 1323

To select an initial item from the drop down list use the following syntax:

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

In your TS code, select the array item as follows:

mySelection = this.myList[1].value; 

Where myList is declared as follows (or use a pre-existing data source within your component):

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

This will initialize the drop down with the Cheque item.

In your table example, just pass the value from your table row element.PaymentMethodName as the initial value in the mat-select as I showed above.

Then your drop down is declared as:

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

Upvotes: 1

Related Questions