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

后端 未结 2 1778
心在旅途
心在旅途 2020-12-31 18:21

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 va

相关标签:
2条回答
  • 2020-12-31 18:57

    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}}
    
    0 讨论(0)
  • 2020-12-31 19:11

    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>
    
    0 讨论(0)
提交回复
热议问题