Abhishek Ekaanth
Abhishek Ekaanth

Reputation: 2567

Angular 4 Selected not working properly when it is given in model?

When I'm trying to give a drop-down menu. By default, I need to select a value that needs to be displayed. When I'm not using a ngModel I'm able to display the default value.

Without ngModel

<select class="form-control">
    <option *ngFor="let type of ListType" [value]="type .id">{{type .name}}</option>
</select>

The Above code works fine when we compile it. I'm able to see first value on the list to be displayed.

enter image description here


With ngModel

<select class="form-control" [(ngModel)]="selectedListType">
    <option *ngFor="let type of ListType" [value]="type .id">{{type .name}}</option>
</select>

enter image description here

This is the display is empty.

Methods tried:

  1. used Selected

<option *ngFor="let type of ListType" [selected]="type.name === 'Dislike'" [value]="type .id">{{type .name}}</option>

  1. used attr.Selected

<option *ngFor="let type of ListType" [ngValue]="type " [attr.selected]="type .name== type.name ? true : null">{{ type.name }}</option>

EDIT

  1. Even Tried to set the selected value via model still no outcome.

Is there any alternative way? Or Am I doing something wrong?

Upvotes: 8

Views: 16304

Answers (3)

Aditya Mittal
Aditya Mittal

Reputation: 1771

I'm using reactive forms and ended up doing something like this to set the default value within my logic:

const defaultTopic = this.myoutline[0].name ? this.myoutline[0].name : '';
this.outline.controls['topic'].setValue(defaultTopic, {onlySelf: true});

Upvotes: 0

AVJT82
AVJT82

Reputation: 73357

You are defining the value for the select as the id value, whereas you are feeding the selectedListType with the name property. So what you want to do is either provide the id value for selectedListType, so for example if your ListType looks like this:

[{id:1, name: 'Dislike'},{...}]

you want to set selectedListyType value as 1. Other option is, if you do not know the id value you can do:

ngOnInit() {
  this.selectedListType = this.ListType.find(x => x.name === 'Dislike').id
}

and your template will then look like this:

<select class="form-control" [(ngModel)]="selectedListType">
  <option *ngFor="let type of ListType" [value]="type.id">{{type.name}}</option>
</select>

Upvotes: 9

Hrishikesh Kale
Hrishikesh Kale

Reputation: 6548

Try Keeping you value and ngModel same like

value = {{type .id}} and [(ngModel)]= "selectedListType.id"

and print the value once it is selected in html

<br>id is {{selectedListType.id}}

Upvotes: 2

Related Questions