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 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.
CodePudding user response:
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 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