VJay
VJay

Reputation: 69

Angular 6 - Default selected option from dropdown

I didn't find any promising answer for my problem. So I am asking something similar. I need to default select a value from dropdown on page load.This drop down appears for each row in data grid. so I have my components as follows. .ts file:


  pwdSelectionItems: any[] = [
      { id: 'CURRENT', name: 'CURRENT' },
      { id: 'FUTURE', name: 'FUTURE' }
    ];

  retrigger(email: CompanyEmailView) {
    let isPwdChoosen = (email.pwdMode === 'CURRENT' || email.pwdMode === 'FUTURE');
    if( !isPwdChoosen ) {
      this.messageService.error('Please select current or future password to retrigger');
    } else {
        this.httpClient.post<any>('/retriggerpasswordemail',
        {id: email.id, emailAddrs: email.emailAddrs, passwordSelection: email.pwdMode }).subscribe(response => {
              this.messageService.success(response.successMessage);
        }, errorResp => {
          if (errorResp.status === 400) {
            this.messageService.error(errorResp.error.errorMessage);
          }
        });
    }
  }

  onPwdChange(pwdsel, email: CompanyEmailView) {
    this.pwdSelection = pwdsel;
    email.pwdMode = pwdsel;
  }

html:

          <select id="choosePwd" name="choosePwd" class="form-control-sm" [(ngModel)]="pwdSelection[$index]"
                  (change)="onPwdChange($event.target.value, entry)">
            <option *ngFor="let mode of pwdSelectionItems" [value]="mode.id"
                    [disabled]="mode.id=='FUTURE' && !(enableFuturePassword && entry.pswdExpiry <= expiryDate)">{{mode.name}}</option>
          </select>
        </td>

Note: I am not initializing anything on page load.

Issues resolved: Selecting an option in first row populates same value in all other rows - Changed model to string[] and resolved. pwdSelection: string[] = []; and used [(ngModel)]="pwdSelection[$index] in <select

Problems:

  1. Dropdown shows default value as blank. Need "CURRENT" option to be default selected.

  2. is there way I can two way bind model without using (change)="onPwdChange($event.target.value, entry)

Thanks for the help.

Upvotes: 2

Views: 528

Answers (1)

Sagar Chaudhary
Sagar Chaudhary

Reputation: 1403

If you want to select a value by default in your dropdown, you need to bind a default value in your [(ngModel)]. For e.g in your example the value of pwdSelection[$index] should be equal to 'CURRENT'. This is the only way possible.

Else you can keep an extra option like;

<option value=undefined> ---Please Select--- </option>
<option *ngFor="let mode of pwdSelectionItems" [value]="mode.id"
                    [disabled]="mode.id=='FUTURE' && !(enableFuturePassword && entry.pswdExpiry <= expiryDate)">{{mode.name}}</option>

Upvotes: 1

Related Questions