a_lovelace
a_lovelace

Reputation: 500

Dropdowns onChange

I've been reading and found that there are lots of variations to this question, but I have not yet found one that worked. This is my HTML:

<select [ngModel]="selectedDepartment" (ngModelChange)="onChange($event)">
   <option *ngFor="let department of Directory.categories" [ngValue]="department.id">{{department.option}}</option>
</select>

My department.option list includes: 'All Departments', 'Department One', and 'Department Two'. Right now, the dropdown starts with a blank selection, and you can only see the options if you click the dropdown arrow. So, the dropdown really acts like: blank, 'All Departments', 'Department One', etc. I want it to use 'All Departments' as a default. I've tried just about every solution I've found here, but have yet to figure out something that actually works. Although this question is very similar to mine, none of the solutions on that page worked for my project.

UPDATE: (the solution)

<select [ngModel]="selectedDepartment" (ngModelChange)="onChange($event)">
    <option *ngFor="let department of Directory.categories" [ngValue]="department">{{department.option}}</option>
</select>

ngOnInit() {
    this.selectedDepartment = this.Directory.categories[0];
}

BUT Now, my onChange($event) is passing an object to the onChange function, so my pipe filter isn't working correctly. This was fixed by using [ngValue]="department.id" and this.Directory.categories[0].id;

Upvotes: 0

Views: 142

Answers (3)

Always Learn
Always Learn

Reputation: 672

I have included the dropdown with values

  On your ts file 
  
      directory:any; 
    this.Directory = [{option: '--sel--', value: 0}];
<select class="selectedDepartment"[(ngModel)]="electrify" (ngModelChange)="electrifyonChange($event)">
               <option *ngFor="let let department of Directory.categories" [ngvalue]="department.id">{{department.option}} </option>
          </select>

Upvotes: 0

Ana
Ana

Reputation: 150

If you have two-way data binding like [(ngModel)]="selectedDepartment", you can also set this in the component ts file

selectedDepartment = 1;

and it will default to that value

Upvotes: 2

user4676340
user4676340

Reputation:

Try this

<select [ngModel]="selectedDepartment" (ngModelChange)="onChange($event)">
   <option *ngFor="let department of Directory.categories; let i = index" [ngValue]="department.id" [selected]="i === 0 ? 'true' : 'false'">{{department.option}}</option>
</select>

Basically, you say that if it's the first option, you set its property to selected.

Upvotes: 1

Related Questions