Search code examples
angulartypescriptdropdown

Select --Please Select-- as default of a dropdown inside a form angular 4.0 html


I have several dropdowns inside a form, however I am not able to make --Please Select-- as default selections of those dropdowns.

I am getting completely plain and blank dropdown. When clicked we can see items have been bound inside it.

HTML

<form novalidate (ngSubmit)="onSubmit(projectinformationFrm)" [formGroup]="projectinformationFrm">
    <select [(ngModel)]="selectedOrganization" placeholder="Organization" formControlName="OrganizationId" (change)="onSelectOrgEdit($event.target.value)" class="form-control">

        <option *ngFor="let org of OrganizationList" [ngValue]="org .OrganizationId" [selected]="org.OrganizationId==selectedOrganization">
        {{ org .OrganizationName }}
        </option>
    </select>

    <div>
        <a class="btn btn-default" (click)="modal.dismiss()"><span class="glyphicon glyphicon-remove"></span>Cancel</a>
        <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-save"></span>Save</button>
    </div>

</form>

Component.ts

public selectedOrganization: number=0;


LoadListforProjectManager(): void {
    try {

        this._service.get(URL)
            .subscribe(data => { this.OrganizationList = data; },
                error => this.msg = <any>error);
    }
    catch (e) {
        this._errorLogService.LogError(e);
    }
}

I am also getting 0,"--Please Select--" as first item of the list from stored procedure.


Solution

  • Instead of getting the first item in the list as Please Select, create it in the Component Template. Also don't use [(ngModel)] along with the ReactiveForms Approach. Something like this:

    <form novalidate (ngSubmit)="onSubmit(projectinformationFrm)" [formGroup]="projectinformationFrm">
        <select placeholder="Organization" formControlName="OrganizationId" (change)="onSelectOrgEdit($event.target.value)" class="form-control">
    
        <option value="null" disabled>Please select</option>
    
        <option *ngFor="let org of OrganizationList" [ngValue]="org .OrganizationId" [selected]="org.OrganizationId==selectedOrganization">
          {{ org .OrganizationName }}
        </option>
      </select>
    
      <div>
        <a class="btn btn-default" (click)="modal.dismiss()"><span class="glyphicon glyphicon-remove"></span>Cancel</a>
        <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-save"></span>Save</button>
      </div>
    
    </form>
    

    Here's a Working Sample StackBlitz for your ref.