Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set first option selected in dropdown list and get value?

I want on load to set select first option in dropdown and then get that value and do something with it. I tried this:

<select class="form-control custom-select" type="text" [(ngModel)]="model" (change)="changeVertical(model)">
                <option value=""></option>
                <option *ngFor="let vertical of ls.registries['verticals'],  let i = index" [(value)]="vertical.code"
                    [attr.selected]='i==1 ? "selected" : null'>
                    {{vertical.name}}</option>
</select>



changeVertical(model) {
        this.changeCategory.emit(model);
    }

But this is not working, it only work if i set i>0 but then it set last element and i dont want to do that. And other thing is that i can not get value because it never enter in this changeVertical method. I tried to get value on ngOnChanges but its same.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Angular automatically selects the entry, which is bound by ngModel. All you need to do is to set ls.registries['verticals'][0].code to model in your ts file.

html

<select class="form-control custom-select" type="text" [(ngModel)]="model" (change)="changeVertical(model)">
  <option value=""></option>
  <option *ngFor="let vertical of ls.registries['verticals']" [value]="vertical.code">
    {{vertical.name}}
  </option>
</select>

ts

this.model = this.ls.registries['verticals'][0].code;

PS.: I recommend to rename model to selectedCode

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading