Amit kumar
Amit kumar

Reputation: 51

How to apply placeholder in select dropdown along with [ngmodel] in angular 6?

whenever I use [(ngModel)] first value becomes empty. but when I remove [(ngModel)] it is working fine.

 <select class="custom-select" id="campaignDropdown" [(ngModel)]="campaignInfo" placeholder="Select Campaign" (change)="hitApiFunction(campaignInfo)">
            <option value="" disabled selected>Select Campaign</option>
              <option *ngFor="let campData of campaigns" [ngValue]="campData"> 
                  {{campData.campaign_name}}
              </option>
            </select>

Upvotes: 3

Views: 4432

Answers (3)

Amit kumar
Amit kumar

Reputation: 51

thank you everyone who tried to give an answer... its working fine now, correct ans is....

<select class="custom-select" id="campaignDropdown" [(ngModel)]="campaignInfo" (change)="hitApiFunction(campaignInfo)">
            <option [value]="0" disabled selected>Select Campaign</option>
              <option *ngFor="let campData of campaigns" [ngValue]="campData"> 
                  {{campData.campaign_name}}
              </option>
            </select>

and in ts file
campaignInfo=0;

Upvotes: 2

Stak
Stak

Reputation: 366

Try to assign the campaignInfo variable with the placeholder text in your component.ts file.

e.g

export class CampaignComponent{
 campaignInfo : any = "";
}

the reason behind such behavior of the placeholder being empty is you are adding ngModel in your dropdown and it is not assign with any text yet. It will work for you because you have option tag value attribute as = ' ' for option Select Campaign thats why assign empty string for campaignInfo variable.

Upvotes: 1

Eudz
Eudz

Reputation: 608

By @Krishna Rathore

You can use [value]="" selected hidden

I have create a demo on Stackblitz

<form role="form" class="form form-horizontal" (ngSubmit)="onSubmit()" #form="ngForm" ngNativeValidate>
    <div class="form-group row">
        <div class="col-xl-4 col-lg-6 col-md-12">
            <fieldset class="form-group">
                <label for="customSelect">Categories:</label>
                <select class="custom-select d-block w-100" id="Category" [(ngModel)]="Category" name="Category" required placeholder="d.ff">
                    <option hidden [value]=""  selected>Select one category </option>
                    <option *ngFor="let item of myBusinessList" [value]="item.id">{{item.name}}</option>
                </select>
            </fieldset>
        </div>
    </div>
    <button type="submit" class="btn btn-raised btn-danger">Save</button>
</form>

Upvotes: 4

Related Questions