angularselectangular-template-form

select first option of dropdown on change event in angular


<select [(ngModel)]="profile.type" name="type"(change)="selectPhoneType($event,mailCreate,'phone4_Value')">
                        <option value="">Select type</option>
                        <option *ngFor="let types of mobiletypes" [ngValue]="types.value">
                          {{types.value}}
                        </option>
                        <option value="addMore">Add More</option>
                      </select>
                    </div>

i have this dropdown when i change the dropdown value it should automatically select the

 selectPhoneType(event,mailCreate,type)
  {
    this.activeType=type;
    event.preventDefault();
    let value = event.target.value;
    if(value=='addMore')
      {
        this.addMailCreateLabel(mailCreate);
        this.profile.type='';
      }
  }

first value but in my case it is not selecting first value after addMore is selected.


Solution

  • It's due to timing issue, from the value being set to AddMore, to being set again to empty string. We can solve it with the below code:

    ...
    if (value == 'addMore') {
          // this.addMailCreateLabel(mailCreate);
          // will execute after the synchronous tasks are done, after which the select picks up the update!
          setTimeout(() => {
            this.profile.type = null;
          });
    }
    ...
    

    Full code:

    import { CommonModule } from '@angular/common';
    import { Component } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { bootstrapApplication } from '@angular/platform-browser';
    import 'zone.js';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [CommonModule, FormsModule],
      template: `
        <select [(ngModel)]="profile.type" name="type" (change)="selectPhoneType($event,mailCreate,'phone4_Value')">
          <option [value]="null">Select type</option>
          <option *ngFor="let types of mobiletypes" [value]="types.value">
            {{types.value}}
          </option>
          <option [value]="'addMore'">Add More</option>
        </select>
      `,
    })
    export class App {
      name = 'Angular';
      mobiletypes = [{ value: 'test' }];
      profile: any = {
        type: null,
      };
      mailCreate = 'Y';
      activeType = '';
      selectPhoneType(event: any, mailCreate: any, type: any) {
        this.activeType = type;
        event.preventDefault();
        let value = event.target.value;
        if (value == 'addMore') {
          // this.addMailCreateLabel(mailCreate);
          setTimeout(() => {
            this.profile.type = null;
          });
        }
      }
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo